有没有一种方法可以使setState同步以解决渲染问题?

问题描述 投票:1回答:2

我面临一个问题。我刚刚发现setState是异步的。如果满足一定条件,我将在我的render方法中渲染组件。

瑞德():

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. 

对此有任何解决方案?

javascript reactjs state
2个回答
1
投票

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

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
}

}


0
投票

您可以将回调传递给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可能会批处理状态更新。

© www.soinside.com 2019 - 2024. All rights reserved.