【问题标题】:setState Cannot Update During Existing State Transition Despite Correct Syntax尽管语法正确,setState 在现有状态转换期间无法更新
【发布时间】:2016-10-10 21:27:28
【问题描述】:

我一直在努力纠正代码中的任何语法错误,但我仍然收到“setState Cannot Update during Existing State”错误。我已经参考了类似的主题,但答案似乎并没有很好地适用于我的情况(或者解决方案失败了)。

这是我定位为有问题的代码:

getInitialState: function() {
        return {
            searching: false,
        anim: new Animated.Value(305),
            user: null,
            isLoaded: false,
            dataSource: new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
      }),
        }
    },
render: function() {
   return <View>
     <View style={styles.mainView}>
        { this.renderProperElement() }
     </View>
}, 
renderProperElement: function() {
        var that = this;
        return <Animated.View
                style={[styles.searchWrapper, {transform: [{translateX: this.state.anim}]}]}>
                <TouchableOpacity style={styles.icon}  onPress={that.startSearch()}>
                    <Image style={styles.icon} source={require('../img/search.png')} />
                </TouchableOpacity>
                <TextInput style={styles.searchInput} autoFocus = {true} />
                <TouchableOpacity onPress={that.stopSearch()} style={styles.icon}>
                    <Image style={styles.icon} source={require('../img/cancel.png')} />
                </TouchableOpacity>
            </Animated.View>
    },
    startSearch: function() {
        this.setState({ searching: true });

        Animated.timing(
             this.state.anim,
             {
                 toValue: 0,
                 easing: Easing.elastic(1),
             }
        ).start();
    },
    stopSearch: function() {
        Animated.timing(
             this.state.anim,
             {
                 toValue: 305,
                 easing: Easing.elastic(1),
             }
        ).start();
    },

特别是这里的代码单挑出了render中函数的调用和startSearch函数:

任何帮助将不胜感激。

【问题讨论】:

    标签: react-native render state setstate


    【解决方案1】:

    当您第一次按下可触摸不透明度时,您已将状态设置为正在搜索:true,但您从未在停止搜索方法中更改过该状态,因此您最好再次在停止搜索方法中将搜索状态更改为 false:

            this.setState({ searching: false });
    

    所以,当您再次设置此搜索状态时,您的应用程序将产生您所需的条件。

    此错误可能是由于尝试使用与之前相同的值更改状态条件而发生的。

    【讨论】:

    • 你指的是startSearch函数吗?如果是这样,我确实在那里将状态设置为 true
    • 哦 - 我明白了 - 是的,我也改变了它,但不幸的是没有运气
    • 否则尝试这样设置:this.setState({searching: !searching});两种情况。
    • 我认为问题在于 setstate 更改本身 - RN 往往不喜欢由渲染触发的状态更改 - 但我不确定是否有任何替代功能
    【解决方案2】:

    在这里找到了答案(尽管 React 现在警告我我正在将一个组件方法绑定到该组件,并且 RN 会自动为我执行此操作(它没有)。

    阅读更多:http://4dev.tech/2016/03/reactjs-error-cannot-update-during-an-existing-state-transition-such-as-within-render-render-methods-should-be-a-pure-function-of-props-and-state/

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 1970-01-01
      • 2017-05-16
      • 2017-05-31
      • 2017-01-05
      • 2016-09-20
      • 2016-12-13
      • 2016-03-31
      • 2016-09-14
      相关资源
      最近更新 更多