有没有办法让 setState 同步来解决渲染问题?

我正面临一个问题。我刚刚发现 setState 是异步的。如果某个条件为真,我将在我的渲染方法中渲染一个组件。


船东 ():


render() {

        const { isFetchingSubject, isFetchingTemplate } = this.props;

        return (

            ...

                            {this.state.showLabelDetails && <Details template={this.props.match.params.templatename} close={this.toggleShowLabelDetails} data={this.state.labelDetails} />}

            ...

        );

    }


onclick 按钮的函数调用:


toggleShowLabelDetails = (event) => {

        if (!this.state.showLabelDetails) this.setState({ labelDetails: JSON.parse(event.target.value) })

        this.setState({ showLabelDetails: !this.state.showLabelDetails });

        if (this.state.showLabelDetails) this.setState({ labelDetails: {} })

    }


状态:


state = { 

        showLabelDetails: false,

        labelDetails: {},

     }


代码在做什么的解释:

  • 当用户点击按钮 X 时,它调用函数 toggleShowLabelDetails()

  • 它将状态中的布尔值更改为 true,并将来自按钮的值添加到作为对象的状态 labelDetails。

  • 状态改变意味着组件将再次渲染,当条件为真时,它将在屏幕上显示一个新组件。

50% 的情况下它运行良好,但有时我会收到以下错误:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

at Object.parse (<anonymous>)


Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. 

有什么解决办法吗?


喵喔喔
浏览 146回答 2
2回答

LEATH

您可以将回调传递给 setState。this.setState(&nbsp; &nbsp; (state, props) => ({showLabelDetails : !state.showLabelDetails}),&nbsp; &nbsp; () => { // Executed when state has been updated&nbsp; &nbsp; &nbsp; &nbsp; // Do stuff with new state&nbsp; &nbsp; &nbsp; &nbsp; if (this.state.showLabelDetails) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({ labelDetails: {} })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })顺便说一句:你不能依赖 setState 中的 this.state (在 react 文档中提到),因为 react 可能会批量更新状态。

慕森卡

你可以尝试做这样的事情:class MyComponent extends Component {function setStateSynchronous(stateUpdate) {&nbsp; &nbsp; return new Promise(resolve => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState(stateUpdate, () => resolve());&nbsp; &nbsp; });}async function foo() {&nbsp; &nbsp; // state.count has value of 0&nbsp; &nbsp; await setStateSynchronous(state => ({count: state.count+1}));&nbsp; &nbsp; // execution will only resume here once state has been applied&nbsp; &nbsp; console.log(this.state.count);&nbsp; // output will be 1}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript