When to use componentWillReceiveProps lifecycle method?

后端 未结 5 972
时光取名叫无心
时光取名叫无心 2020-12-04 23:51

I am new to React/Redux and have a problem with state.

TrajectContainer.jsx

class TrajectContainer extends React.Component {
    con         


        
5条回答
  •  忘掉有多难
    2020-12-05 00:36

    The problem with your implementation is that you are duplicating your Redux store state (comming from the props) into your React state (this.state)

    In your example, if store.trajects is updated, then this.props.traject will be updated and a render will be triggered only if this.props.traject is used in your render method (not the case).

    Since you are using the state instead of the prop in your render method, you have to manually change the state of you component using this.setState to trigger a render.

    This is not a good pattern: I would advise not to use the state, and use directly the props like this:

    class TrajectContainer extends React.Component {
        render() {
            return (

    Trajects

    {this.props.trajects.map(traject => )}
    ) } } const mapStateToProps = function (store) { console.log('mapToStateProps', store); return { trajects: store.trajects }; }; const mapDispatchToProps = function (dispatch, ownProps) { return { onClick: function () { dispatch(addTraject()); } } }; export default connect(mapStateToProps, mapDispatchToProps)(TrajectContainer)

提交回复
热议问题