javascript - After webpack splits and loads the code, the react interface does not update
黄舟
黄舟 2017-06-26 10:53:01
0
1
743

After webpack splits and loads the code, the react interface is not updated.
Post the code first

main.js

export default class extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            textview: undefined,
            text: 'text'
        }
    }
    _loadText() {
        if (!this.state.textview)
            require.ensure([], require => {
                const Text = require('./text').default;
                this.setState({
                    textview: <Text text={this.state.text} />
                })
            })
    }
    render() {
        return (
            <p>
                <p>Main</p>
                <button onClick={() => this._loadText()}>load</button>
                <button onClick={() => this.setState({ text: 'change' })}>change</button>
                {this.state.textview}
            </p>
        )
    }
}

text.js

export default class extends React.Component {
    render() {
        return (
            <p>{this.props.text}</p>

        )
    }
}

After clicking load, the text control can be loaded and displayed.
But when clicking change to change the state, the text control will not be refreshed.
Print log this.state.text has changed.

I’ve been looking for it for a long time but I still don’t know what the problem is. Please ask God T.T
Thank you

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
漂亮男人

The problem lies in the textview: <Text text={this.state.text} /> of _loadText in main.js

Your way of writing actually tells React that when I load, give me a Text component, and the attribute is this.state.text (in this example, it is 'text') , this.state.textview will not be updated when the parent component is updated

Just change it like this

In the

_loadText () function, change the content of this.setState

this.setState({
    textview: Text
})

render () function

<p>
    <p>Main</p>
    <button onClick={() => this._loadText()}>load</button>
    <button onClick={() => this.setState({ text: 'change' })}>change</button>
    {this.state.textview ? React.createElement(this.state.textview, { text: this.state.text }) : null}
</p>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template