据我了解,您要做的就是将组件的props转换为组件自己的状态。您总是可以
componentWillReceiveProps像这样在组件的生命周期方法中将组件的props更改为组件的状态。
//componentclass MyComponent extends Component { componentWillReceiveProps(newProps){ if(newProps.variableInProps != this.props.variableInProps){ this.setState({variableInState: newProps.variableInProps }) } } render() { (<div onClick={this.props.executeAction.bind(this)}> {this.state.variableInState} </div>) } someOtherMethod() { // I want to operate with state here, not with props // that's why my div gets state from this.state instead of this.props this.setState({variableInState: 'somevalue'}) }}export default connect((state, ownProperties) => { return { // So I want to change MyComponent.state.variableInState here // but this method updates MyComponent props only // What can I do? variableInProps: state.myVariable }}, {executeAction})(MyComponent);
componentWillReceiveProps每当有新的道具进入组件时,方法总是由react执行,因此这是根据道具更新组件状态的正确位置。
更新:
The
componentWillReceivePropshas been deprecated. So instead of this method
you can use
componentDidUpdatemethod to do this.
componentDidUpdate
method takes previous props and previous state as arguments. So you can check
for the change in props and then set the state.
componentDidUpdate(prevProps) { if(prevProps.variableInProps !== this.props.variableInProps){ this.setState({variableInState: this.props.variableInProps }) }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)