Javascript 如何在渲染内部设置状态?

Javascript 如何在渲染内部设置状态?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,首先,我尝试检查用户的id是否与DB中的id匹配。如果是这样,则为hasappliced和toggle设置一个新状态,但我收到以下警告在现有状态转换期间无法更新(例如在“渲染”或其他组件内). 我甚至试着调用一个函数,它在render之外,并且说了同样的话。但是如果我从按钮组件调用render byonPress={}方法之外的函数,那么一切都很好。但是在这种情况下,当用户访问页面时,我需要首先检查此项,如果已应用返回false,则使用按钮 render() { let { ha

首先,我尝试检查用户的id是否与DB中的id匹配。如果是这样,则为
hasappliced
toggle
设置一个新状态,但我收到以下警告
在现有状态转换期间无法更新(例如在“渲染”或其他组件内).

我甚至试着调用一个函数,它在render之外,并且说了同样的话。但是如果我从按钮组件调用render by
onPress={}
方法之外的函数,那么一切都很好。但是在这种情况下,当用户访问页面时,我需要首先检查此项,如果
已应用
返回
false
,则使用按钮

render() {
        let { hasApplied } = this.state;
        let { toggle } = this.state;
        let matchUserId = [];
        const textValue = toggle ? 'APPLIED' : 'APPLY NOW';
        const buttonBg = toggle ? '#848d95' : '#34ed1c';
        const buttonState = toggle ? 'false' : 'true';
        const { navigation } = this.props;
        const { goBack } = this.props.navigation;
        const { jobBusiness, locationBusiness } = this.props.navigation.state.params;
        let { user, location, job, data, business } = this.props.navigation.state.params;

        // Check the available applied ids and concatenate objects in Array
        // Check if user_id match any of appliedUserId 
        if (!hasApplied) {
            job.applied.map(o => {
                matchUserId.push(o.user_id);
            });
            const resultUserId = [].concat.apply([], matchUserId);
            hasApplied = resultUserId.includes(this.props.user_id)
            // this.onButtonPress()
            this.setState({hasApplied: true, toggle: true})
        }
有人能找到解决办法吗


感谢使用React,您不应该也不需要在render()中设置state

我建议将状态检查放在componentDidMount()中。这样做的目的是保证在呈现组件时在componentDidMount()函数中执行任何代码,从而允许您执行检查、设置等

基本上,要做到这一点:

componentDidMount() {
    // check if the user ID matches what's in the database
    // if the above is true, setState as needed
}
请注意,可以使用三元表达式在React渲染中显示或不显示内容。让我举一个例子:

    { (this.state.whateverStateYouWantToCheck)
      ? <div className="class-of-your-choice">Content you wish to display.</div>
      : null }
{(this.state.whateverstate您要检查)
?您希望显示的内容。
:null}
在上面的示例中,如果this.state.whateverStateYouWantToCheck为true,则将呈现“?”后面的代码。如果为false,则不会呈现任何内容(null)

最后一件事,因为我不知道在这种情况下您的组件/容器结构是什么,所以我不确定您引用的用户标识是存储在这个组件还是父容器中。如果它在父容器的状态中可用,您肯定希望将其作为道具传递下去。如果您对实现此功能有任何疑问,请告诉我


使用我描述的方法,您可以在这里找到一个很好的解决方案。

可能重复的代码没有理由不能在另一个组件方法中使用该代码。React已阻止从render方法调用setState,因为存在无限循环的可能性。见这个问题: