将属性映射到react-redux中的状态

dea*_*908 8 javascript reactjs redux react-redux

我有一个用于state向用户提供数据的组件.例如<div>this.state.variableInState</div>.该组件可以调度某些方法(例如on onClickaction).我目前使用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);
Run Code Online (Sandbox Code Playgroud)

Pra*_*rma 8

无论我理解什么,你想要做的就是将组件的道具转换为组件自己的状态.您可以随时在组件的componentWillReceiveProps生命周期方法中将组件的props更改为组件的状态,如下所示.

//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);
Run Code Online (Sandbox Code Playgroud)

componentWillReceiveProps 每当新道具进入组件时,方法总是通过响应来执行,因此这是根据道具更新组件状态的正确位置.

  • componentWillReceiveProps已经被弃用,您可以改为使用componentDidUpdate, (2认同)