写作时间:2020年末吧具体时间记不得了
开发平台:windows
React-Native版本:0.63.4
目标平台:Android、iOS
变量什么时候使用state来维护
1、变量如果是通过props从父组件中获取,就不要使用state
2、如果这个变量可以通过其他的状态state或者属性props通过数据处理得到,不要使用state
3、如果变量在render中没有使用到,那就不是一个state
4、变量在整个生命周期中都保持不变时,也不是一个state
总的来说:
State是可变的,是组件内部维护的一组用于反映组件UI变化的状态集合
Props对于使用它的组件来说,是只读的,要想修改Props,只能通过该组件的父组件修改
如何处理setState异步的问题
下面这段代码希望实现的效果是:当点击按钮,count可以由1变为4,并重新渲染。但最终结果无法达到预期,原因是add方法是从this.state.count中读取数据的,但是React不会更新this.state.count,直到该组件被重新渲染,所以最终每次add读取this.state.count的值都是1,并最终将它设为2
import React from 'react';
import {SafeAreaView, StyleSheet, Text, Button} from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1,
};
}
render() {
return (
<SafeAreaView style={styles.container}>
<Text>{this.state.count}</Text>
<Button title={'button'} onPress={this._onBtnPress} />
</SafeAreaView>
);
}
_onBtnPress = () => {
this._add();
this._add();
this._add();
};
_add = () => {
this.setState({
count: this.state.count + 1,
});
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'cyan',
},
});
修改方法如下:
方法1:由传递对象改为传递方法
修改后的add方法如下:
_add = () => {
this.setState((state) => {
return {count: state.count + 1};
});
};
方法2:利用回调,在state修改完成之后再执行
修改后的add方法如下:
_add = () => {
this.setState(
{
count: this.state.count + 1,
},
() => {
this.setState(
{
count: this.state.count + 1,
},
() => {
this.setState({
count: this.state.count + 1,
});
},
);
},
);
};