当我需要在渲染中设置状态时在哪里设置状态?

Where to set state when I need that state in render?

我收到以下错误:

react_devtools_backend.js:2430 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

从错误中,我知道我得到它是因为我在渲染中设置状态。

但我不确定在哪里设置状态,因为我需要那个状态元素,developerTitle 在 render 方法的更下方。

如果不在渲染中,我可以把它放在哪里?

谢谢!

这是我的代码:

export default class Game extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            developerTitle: ''
        }
    }

    render() {
        const { indieDeveloperId } = this.props;
        this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
        
            <div>

                <h3>{this.state.developerTitle}</h3>
                ...
                ...
            </div>
    }
    
    //by-indie-developer/{indieDeveloperId
    async getDeveloperTitle(indieDeveloperId) {
        const r = await axios.get(`/api/developer/by-indie-developer/${indieDeveloperId}`);
        const developerTitle = r.data;
        this.setState({
            ...this.state, ...{
                developerTitle: developerTitle
            }
        });
    }
}

您无法在 render() 中设置状态。但是您可以在使用 componentDidMount() 函数加载组件时设置状态。 将具有该名称的函数添加到您的组件中:

componentDidMount() {
        this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
}

您不必调用该函数。状态会自动设置。