我正在构建一个表,状态需要在某处初始化,哪些数据最终通过fetch更新。
我的问题是表需要在服务器端呈现,因此在安装组件之前需要在服务器上呈现数据,我不能使用componentDidMount。
我可以使用props在render()方法中渲染表格内容,但是当表格不依赖于通过道具接收数据但是通过调用api时,如何更新数据呢?
我的结论是我必须使用状态,但初始化状态与道具似乎是一个很大的不,所以我在一个困境。
在不违反规则的情况下,您对初始化组件状态有何建议?
我的意思是:让你的组件通过使用默认值初始化状态来挂载一个空表,并向你的组件添加一个函数,该函数从你所说的数据应该来自哪里取。当对您的应用程序有意义的事件发生时,可以调用此函数。
让我知道是否以及为什么不起作用,以及您遇到的其他问题。
您可以使用props初始化状态。这没有问题。
我的方法是:
锅炉板示例:
class Component1 extends React.Component{
constructor(props) {
super(props)
this.state = {
tableData: props.tableData
}
}
componentDidMount() {
//Make API call here
callAPItoGetData()
}
componentWillReceiveProps(nextProps) {
const { tableData } = nextProps
if(tableData !== this.state.tableData ) {
//You need to make sure that this condition is fullfiled only once to avoid setting state multiple times
this.setState({
tableData: nextProps.tableData
})
//Alternatively, an action can be dispatched to update the redux-store which will update the props and cause re-render with new data
}
}
render() {
return (
<div>{/*render table here*/}</div>
)
}
}
希望能帮助到你。回复任何疑惑/困惑。
对于React Hooks和useEffect钩子来说,这将是一个很好的例子。根据文件:
您可以将useEffect Hook视为componentDidMount,componentDidUpdate和componentWillUnmount的组合。
下面是一个简单的示例,其中组件首先将prop数据作为状态,但是一旦API调用完成,它就会更改为API数据:
import React, { useState, useEffect } from "react";
function DataList(props) {
const [users, setUsers] = useState(props.propData);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => {
setUsers(data);
});
});
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user.name}</li>
))}
</ul>
);
}
export default DataList;