将属性映射到react-redux中的状态
我有一个用于state
向用户提供数据的组件。例如<div>this.state.variableInState</div>
。该组件可以调度某些方法(例如,按onClick
操作)。我目前正在使用react-
redux一种connect
方法来映射store
到props
。setState
派遣后有办法吗?
// actionsexport 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更改为组件的状态。
//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 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(prevProps) { if(prevProps.variableInProps !== this.props.variableInProps){
this.setState({variableInState: this.props.variableInProps })
}
}
以上是 将属性映射到react-redux中的状态 的全部内容, 来源链接: utcz.com/qa/411021.html