为什么RN在使用setState时就像forceUpdate一样使用setState

时间:2015-12-22 06:33:52

标签: react-native

请看一下这个非常简单的例子

'use strict';
var React = require('react-native');
var {
    AppRegistry, Text, TextInput, View
} = React;
var bString = 'b init';
var Example = React.createClass({
    getInitialState: function() {
        return {
            aString: 'a init',
            cString: 'c init'
        };
    },
    changedString: function(aEvent) {
        bString = 'b changed';
        this.state.cString = 'c changed';
        this.setState((state) => {
            return {
                aString: 'a changed'
            };
        });
    },
    render: function() {
        return (
            <View style={{flex: 1}}>
                <Text>
                    {this.state.aString}{'\r\n'}{bString}{'\r\n'}{this.state.cString}
                </Text>
                <Text onPress={this.changedString}>
                    Ppppppppppppppppppppp......press me
                </Text>
            </View>
        );
    },
});
AppRegistry.registerComponent('Project16N', () => Example);

我在移动设备的屏幕上只考虑aString,而在调用changedString时更改了changedString。但是,当aString被调用时,bStringCStringthis.setState( balabala...)都会发生变化。那么我们为什么要使用this.forceUpdate

为什么我们不使用setState呢?

forceUpdatesection { float: left; margin-right: 5%; margin-left: 5%; width: 55%; padding-top: 10px; } aside { margin-right: 5%; width: 40%; margin-left: 5%; padding-top: 10px; float: right; } footer { height: 30px; background-color: #ca171b; border-radius: 10px; border-bottom-style: groove; border-bottom-color: rgba(0,0,0,1); border-bottom-width: 8px; border-left-style: ridge; border-left-color: rgba(0,0,0,1); border-left-width: 3px; border-right-width: 3px; border-right-style: ridge; border-right-color: rgba(0,0,0,1); font-family: "Arial Rounded MT Bold"; font-size: 1.2em; color: #FFFFFF; text-align: center; font-weight: bold; margin: 5%; padding-top: 5px; padding-bottom: 5px; z-index: 1; } 之间的区别在哪里?

1 个答案:

答案 0 :(得分:2)

因为您正在changedString函数中修改this.state对象。

根据经验,你永远不应该直接修改this.setState()上的任何内容,你应该将它视为不可变的,而是使用this.setState修改状态,因为你刚才使用的突变可能会被覆盖do shell script在稍后阶段,当你直接改变状态时,通常会更难推断你的申请。

docs有一个很好的解释方法。

相关问题