Javascript 对ReactJS中的道具更改采取行动
我需要在React组件中使用当前道具和以前的道具值。 所以我就这样做了Javascript 对ReactJS中的道具更改采取行动,javascript,reactjs,Javascript,Reactjs,我需要在React组件中使用当前道具和以前的道具值。 所以我就这样做了 state = { current: null, previous: null, }; componentWillReceiveProps(nextProps) { if (nextProps.amount !== this.state.current) { this.setState({previous: this.state.current, current: nextProps
state = {
current: null,
previous: null,
};
componentWillReceiveProps(nextProps) {
if (nextProps.amount !== this.state.current) {
this.setState({previous: this.state.current, current: nextProps.amount});
}
}
...
render() {
const {previous, current} = this.state;
return (
...
<CountUp className="counter" start={previous} end={current} duration={1}/>
...
)
}
状态={
当前:空,
上一个:空,
};
组件将接收道具(下一步){
if(nextrops.amount!==this.state.current){
this.setState({previous:this.state.current,current:nextrops.amount});
}
}
...
render(){
const{previous,current}=this.state;
返回(
...
...
)
}
这样做很好,但这样做好吗?还有其他“好”方法吗?您可以在
setState
对象中使用箭头函数。
像这样:
this.setState((prevState)=>{
返回{yourState:prevState.yourState}
})
从v16.2.0
开始,组件将接收道具
是根据道具更改更新状态的正确位置,并且由于您希望在渲染中同时使用当前状态和以前的状态,因此需要在执行时维护两个不同的状态变量
但是,当您基于以前的状态更新状态时,请使用functional setState方法
查看此答案以了解更多详细信息
根据最新的RFC做出反应
从道具/状态派生的状态
此模式的目的是计算从道具导出的一些值,以便在渲染期间使用
通常,组件将接收道具
用于此,但如果计算速度足够快,可以在渲染
中完成:
从v16.3.0开始,您将使用
static getDerivedStateFromProps(nextProps, prevState) {
if (
!prevState ||
prevState.current !== nextProps.amount
) {
return {
previous: prevState.current,
current: nextProps.amount
};
}
}
我想为从谷歌来到这里的其他人更新这个答案。从
v16.8.6
开始,组件WillReceiveProps
已标记为遗留,不建议使用。相反,您应该使用componentdiddupdate
并根据新的道具和以前的道具/以前的状态更新您的状态
componentDidUpdate(prevProps, prevState) {
if (this.props.someVal !== prevState.someVal) {
this.setState({ previous: prevState.someVal, current: this.props.someVal });
}
}
显然,你是否检查之前的状态或之前的道具取决于你的判断/情况。您可以使用参数或不使用参数来实现componentdiddupdate
,但如果需要prevState
,则必须声明prevProps
setState(prevState)
由React提供,以及道具,这两种道具都是可选的。对于2019年阅读本文的任何人,请查看我的。不建议使用组件WillReceiveProps
@如果您的答案不正确,最好使用getDerivedStateFromProps
componentDidUpdate(prevProps, prevState) {
if (this.props.someVal !== prevState.someVal) {
this.setState({ previous: prevState.someVal, current: this.props.someVal });
}
}