【问题标题】:redux check state at componentWillMount在 componentWillMount 的 redux 检查状态
【发布时间】:2017-04-24 19:48:49
【问题描述】:

在我的 react 组件中,状态中有两个属性,一个在本地反应状态,另一个在 Redux 存储中。

    componentWillMount() {
      this.props.fetchExercise(this.props.params.id);
    }    
     constructor(props) {
       super(props); 
       this.state = {editeMode: false}
   }

    function mapStateToProps(state) {
      return {currentExercise: state.currentExercise}
   }

    export default connect(mapStateToProps, {fetchExercise})(createNewExercisePage);

所以根据路径; /new-exe/:id Redux 中的 currentExercise 要么是空的,要么是获取了一些东西。 editeMode 在 React 中。现在我想检查currentExercise editemode:true 中是否有东西,否则它应该是错误的(根据 false 和 true,我正在显示不同的按钮)。 我在componentWillMount(){... this.setState({editeMode:_.isNull(this.props.currentExercise)})} 中尝试过(使用 lodash) 但它不起作用,它仍然是错误的。 一般来说,在这些情况下,首先应该获取一些东西然后检查它,应该是什么方法。

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    您应该避免在 componentWillMount (docs) 中引入任何副作用或订阅。文档还说“在这个方法中设置状态不会触发重新渲染”,所以我猜这意味着设置的值将被忽略。

    除非this.props.currentExercise 的值发生更改,否则您不会更改存储中的editeMode 条目的值,因此跟踪更改以更新存储没有多大用处。直接使用该值即可。在您的特定情况下,我会执行以下操作:

    componentWillMount() {
      this.props.fetchExercise(this.props.params.id);
    }    
    constructor(props) {
       super(props); 
       this.state = {}
    }
    
    render(){
        const editeMode = _.isNull(this.props.currentExercise);
        // The rest of your render logic, using editeMode instead of this.state.editeMode
    }
    
    function mapStateToProps(state) {
       return {currentExercise: state.currentExercise}
    }
    
    export default connect(mapStateToProps, {fetchExercise})(createNewExercisePage);
    

    【讨论】:

      【解决方案2】:

      将代码放入 componentWillReceiveProps

      componentWillReceiveProps(nextProps) {
        this.setState({ editeMode: !nextProps.currentExercise) });
      }
      

      Redux 会确保 props 得到更新。

      您还应该考虑将 editMode 状态改为在 Redux 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 2016-06-17
        • 2018-03-15
        • 1970-01-01
        • 2021-02-14
        • 2020-09-11
        相关资源
        最近更新 更多