我有一个使用的组件state
向用户提供数据。例如<div>this.state.variableInState</div>
。该组件可以调度一些方法(例如onClick
行动)。我目前正在使用react-redux
an connect
映射方法store
to 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 转换为组件自己的状态。您可以随时将组件的 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
每当组件有新的 props 时,react 都会执行该方法,因此这是根据 props 更新组件状态的正确位置。
UPDATE :
The componentWillReceiveProps
已被弃用。因此,您可以使用以下方法来代替此方法componentDidUpdate
方法来做到这一点。componentDidUpdate
方法将之前的 props 和之前的状态作为参数。所以你可以检查 props 的变化,然后设置状态。
componentDidUpdate(prevProps) {
if(prevProps.variableInProps !== this.props.variableInProps){
this.setState({variableInState: this.props.variableInProps })
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)