javascript - 如何在渲染 react native 中设置状态

标签 javascript reactjs react-native

当我想在渲染生命周期中设置状态时,它给了我这个错误

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

changeInitial(){
   this.setState({initialLoad: false});
}

render() {
    if (this.state.initialLoad) {
        Animated.timing(this.state.listPosition, {
            toValue: 350,
            duration: 2000,
        }).start(() => this.changeInitial());
    }
 }

最佳答案

您不应在 render() 方法内使用 setState(),因为它会在渲染器内触发重新渲染,从而引发错误。更好的方法是在 componentDidMount() 方法内部,如下所示:

changeInitial(){
   this.setState({initialLoad: false});
}
componentDidMount(){
    if (this.state.initialLoad) {
       Animated.timing(this.state.listPosition, {
           toValue: 350,
           duration: 2000,
       }).start(() => this.changeInitial());
    }
}
render() {
    // Your component template here
}

关于javascript - 如何在渲染 react native 中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022278/

相关文章:

javascript - 让 <div> 和 <a> 并排具有相同的高度

javascript - 如何跳过此 js 的边距顶部?

reactjs - React useRef未定义

javascript - 如何在 JavaScript 中使用构造函数和更新构造函数值

reactjs - react native 导航栏位置

javascript - NgIf 里面点击 Angular

javascript - 如何使用 for 循环更改字体大小

ios - React-Native - 将应用程序发送到 iPhone 进行测试的最佳方式

javascript - ReactJS:如何根据 parent 的 Prop 隐藏元素?

javascript - 我该如何解决这个问题 : "node_modules/expo/AppEntry.js: [BABEL]"?