search

Home  >  Q&A  >  body text

javascript - After webpack splits and loads the code, the react interface does not update

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

黄舟黄舟2756 days ago744

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-06-26 10:55:01

    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>

    reply
    0
  • Cancelreply