我有一个用于state向用户提供数据的组件。例如<div>this.state.variableInState</div>。该组件可以调度某些方法(例如,按onClick操作)。我目前正在使用react- redux一种connect方法来映射store到props。setState派遣后有办法吗?
state
<div>this.state.variableInState</div>
onClick
react- redux
connect
store
props
setState
// actions export function executeAction() { return function (dispatch, getState) { dispatch({ type: 'MY_ACTION', payload: axios.get('/some/url') }); }; } // reducer export default function (state = {}, action) { switch (action.type) { case 'MY_ACTION_FULFILLED': return {...state, myVariable: action.payload.data} } } //component class MyComponent extends Component { 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);
据我了解,您要做的就是将组件的props转换为组件自己的状态。您总是可以componentWillReceiveProps像这样在组件的生命周期方法中将组件的props更改为组件的状态。
componentWillReceiveProps
//component class 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 componentWillReceiveProps has been deprecated. So instead of this method you can use componentDidUpdate method 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
componentDidUpdate(prevProps) { if(prevProps.variableInProps !== this.props.variableInProps){ this.setState({variableInState: this.props.variableInProps }) } }