Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

reactjs - Why won't parent props get updated in dynamically created child Components (that are generated once)

Playing with performance and seeing if saving the state of dynamically generated components on componentDidMount() essentially creates performance improvement.

I see that {...this.props} only represents the props passed on the initial creation. Updates to the parent props does not trickle down on render() update.

This makes sense given React architecture but doesn't given JS referencing. Is it because this.props is merely an update of props, not an actual variable reference?

Musings: This would seem most performant method of dynamic components because they are generated only once. But it loses React's tracking ability I guess, why wouldn't React maintain understanding that these Views are grabbing {..this.props}.

// Inline Render
class MyDynamicViews extends React.Component {


    state = {
        views: []
    }

    componentDidMount() {

        let json = [{
            view: 1
        }, {
            view: 2
        }, {
            view: 3
        }];

        let views = json.map((view, i) => {
            return <View key={i} {...this.props}>{view.i}</View>
        });

        this.setState({views});

    }

    render() {
        return <View>{this.state.views}</View>

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

views returns <View key={i} {...this.props}>{view.i}</View> and you're setting this element using setState. This is not correct way to do. You would need to do like below:

class MyDynamicViews extends React.Component {
    state = {
        views: []
    }
    componentDidMount() {
        // now, you want to update the state
        // I suppose you're going to update the state fetching the data
        // thus, placed your new state data same here
        let views = [{
            view: 1
        }, {
            view: 2
        }, {
            view: 3
        }];
        this.setState({views});
    }
    render() {
        const views = this.state.views
        return views && views.map((view, i) => (
          <View key={i} {...this.props}>{view}</View>
        ))
    }
}

Now, you'll get your component working fine and without any issue with props.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...