为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2021-10-29 17:19:11
我正面临一个问题。我刚刚发现 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 0at Object.parse (<anonymous>)Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. 有什么解决办法吗?
查看完整描述

2 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

您可以将回调传递给 setState。


this.setState(

    (state, props) => ({showLabelDetails : !state.showLabelDetails}),

    () => { // Executed when state has been updated

        // Do stuff with new state

        if (this.state.showLabelDetails) {

            this.setState({ labelDetails: {} })

        }

    }

)

顺便说一句:你不能依赖 setState 中的 this.state (在 react 文档中提到),因为 react 可能会批量更新状态。


查看完整回答
反对 回复 2021-10-29
?
慕森卡

TA贡献1806条经验 获得超8个赞

你可以尝试做这样的事情:


class MyComponent extends Component {


function setStateSynchronous(stateUpdate) {

    return new Promise(resolve => {

        this.setState(stateUpdate, () => resolve());

    });

}


async function foo() {

    // state.count has value of 0

    await setStateSynchronous(state => ({count: state.count+1}));

    // execution will only resume here once state has been applied

    console.log(this.state.count);  // output will be 1

}

}


查看完整回答
反对 回复 2021-10-29
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信