我发现这篇关于创建 MERN 项目的教程文章https://medium.com/swlh/how-to-create-your-first-mern-mongodb-express-js-react-js-and-node-js-stack-7e8b20463e66 . 一切正常,但我对componentDidMount()
MoviesList.jsx 文件中的函数内部代码感到困惑:
import React, { Component } from 'react'
import ReactTable from 'react-table'
import api from '../api'
import styled from 'styled-components'
import 'react-table/react-table.css'
const Wrapper = styled.div`
padding: 0 40px 40px 40px;
`
class MoviesList extends Component {
constructor(props) {
super(props)
this.state = {
movies: [],
columns: [],
isLoading: false,
}
}
componentDidMount = async () => {
this.setState({ isLoading: true })
await api.getAllMovies().then(movies => {
this.setState({
movies: movies.data.data,
isLoading: false,
})
})
}
render() {
const { movies, isLoading } = this.state
console.log('TCL: MoviesList -> render -> movies', movies)
const columns = [
{
Header: 'ID',
accessor: '_id',
filterable: true,
},
{
Header: 'Name',
accessor: 'name',
filterable: true,
},
{
Header: 'Rating',
accessor: 'rating',
filterable: true,
},
{
Header: 'Time',
accessor: 'time',
Cell: props => <span>{props.value.join(' / ')}</span>,
},
]
let showTable = true
if (!movies.length) {
showTable = false
}
return (
<Wrapper>
{showTable && (
<ReactTable
data={movies}
columns={columns}
loading={isLoading}
defaultPageSize={10}
showPageSizeOptions={true}
minRows={0}
/>
)}
</Wrapper>
)
}
}
export default MoviesList
为什么我们必须在此代码中设置 isLoading: true this.setState({ isLoading: true })
,然后使用此代码将其设置回 false :
await api.getAllMovies().then(movies => {
this.setState({
movies: movies.data.data,
isLoading: false,
})
})
我已经为这个问题苦苦挣扎了将近一个星期。我真的需要帮助来理解这段代码。先感谢您。