如果使用的是getDerivedStateFromProps函数,如何设置状态?
例如,我有以下内容:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.data.imo && nextProps.data.imo !== prevState.imo) {
fetch('http://localhost:3001/get/latestcalls/' + nextProps.data.imo)
.then(res => res.json())
.then((data) => {
console.log('got data: ',data);
prevState.latestcalls = data;
return ({latestcalls: data})
})
.catch('Error: ', console.log)
}
return null;
}和
render() {
console.log(this.state.latestcalls);
return (...在render函数中,this.state.latestcalls总是落后的,即prevSate。
问题
在getDerivedStateFromProps函数中,我得到数据,并需要设置当前状态。这个是可能的吗?
因为它是static,所以我不能调用this.setState...。
谢谢
发布于 2020-01-19 18:24:43
我认为你必须用componentDidMount和componentDidUpdate来表示React.Component或useEffect表示React.FC。getDerivedStateFromProps文档你可以找到
如果您需要执行副作用(例如,数据获取或动画)以响应道具的更改,则使用
componentDidUpdate生命周期。
class MyComponent extends React.Component {
constructor(props) {
this.state = {
latestcalls: null,
};
}
componentDidMount() {
const { data: { imo } } = this.props;
if (imo) {
this.fetchData();
}
}
componentDidUpdate(prevProps) {
const { data: { imo: prevImo } } = prevProps;
const { data: { imo: nextImo } } = this.props;
if (prevImo !== nextImo) {
this.fetchData();
}
}
fetchData() {
const { data: { imo } } = this.props;
fetch(`http://localhost:3001/get/latestcalls/${imo}`)
.then(res => res.json())
.then((data) => {
this.setState({ latestcalls: data, });
})
.catch('Error: ', console.log);
}
render() {
return null;
}
}对于React.FC
const MyComponent = ({ data: { imo } }) => {
const [latestcalls, setLatestcalls] = React.useState(null);
React.useEffect(() => {
if (imo) {
fetch(`http://localhost:3001/get/latestcalls/${imo}`)
.then(res => res.json())
.then((data) => {
setLatestcalls(data);
})
.catch('Error: ', console.log);
}
}, [imo]);
return null;
}发布于 2020-01-19 17:48:58
getDerivedStateFromProps非常罕见地需要在state更改后重新生成props。它不打算像您展示的那样实现异步逻辑。这就是为什么它是static:它只是一个纯同步函数。
componentDidUpdate是这样做的自然之地。
componentDidUpdate(prevProps, prevState) {
if (this.props.data.imo && this.props.data.imo !== prevState.imo) {
fetch('http://localhost:3001/get/latestcalls/' + nextProps.data.imo)
.then(res => res.json())
.then((latestcalls) => {
this.setState({latestcalls})
})
.catch('Error: ', console.log)
}
}https://stackoverflow.com/questions/59812708
复制相似问题