2016-12-09 15 views
1

私の反応コンポーネントでは、私は2つの属性を持っている、1つはローカルの反応状態にあり、もう1つはReduxストアにあります。reduxチェック状態をcomponentWillMount

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にあります。今私は私が何かを持っているかどうかをチェックしたいと思うcurrentExerciseeditemode:trueそれ以外の場合はfalseでなければならない(falseとtrueによると私は異なるボタンを表示している)。 componentWillMount(){... this.setState({editeMode:_.isNull(this.props.currentExercise)})} で試してみましたが(ロダッシュ付き)試してもうまくいかず、嘘です。 これらの場合、まず最初に何かを取得してチェックして、それではどうすればよいのでしょうか。

答えて

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); 
+0

ありがとう、それは働いた –

1

componentWillReceivePropsにコードを入れます。

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

Reduxは小道具が更新されるようにします。

また、editMode状態をReduxに入れることを検討する必要があります。

関連する問題