一、数组操作1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41export default class LabelMedia extends Component {
constructor(props) {
super(props);
this.state = {
children: []
};
}
addItem(item){
this.setState({
children: [
...this.state.children,
item
]
})
}
addDataSet(dataSet){
//不好的写法,问题出在this.state.children,不推荐
this.setState({
children: this.state.children.concat(dataSet)
})
//推荐写法
this.setState((prevState, props)=>({
children: prevState.data.concat(dataSet)
}))
//总结: this.setState既可以传对象,也可以是个方法,推荐用方法,因为可以获取到上一次的state值
}
removeItem(item){
this.setState({
children: this.state.children.filter( (item) =>{
return item !== path
})
})
}
}
续:如果在setState后,要立即将给变量值回传给父类,供父类操作。上面这么写是不行的。例如:1
2
3
4
5
6
7
8
9addItem(item){
this.setState({
children: [
...this.state.children,
item
]
})
console.warn('result: ' + this.state.children);
}
你会发现,打印出来的根本不是你想要的结果。这就是react native的机制。 setState后,得要在render生命周期函数中,才是真正更改的结果。
毕竟setState是耗时的,涉及到界面的刷新。所以是异步操作。不能立即取。要立即获取变量值,可以这样写:1
2
3
4
5
6
7addItem(item){
let data = [...this.state.children, item];
this.setState({
children: data
});
console.warn('result: ' + data);
}
这样就可以了。 removeItem方法同上。
二、哪些生命周期函数中可以调用setState
首先render方法是肯定不可能调用setState方法的,想想都知道会陷入无限死循环。一般是在 constructor, componentDidComponent两个生命周期函数中。今天看github上
react-native-progress-button源码。发现 componentWillReceiveProps也可以调用。关键代码记录如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class ProgressButton extends React.Component {
constructor(props) {
super(props);
this.state = {
progressValue: 0,
};
}
componentWillReceiveProps(nextProps){
this.state.progressValue.setValue(this._calculateProgressToWidth(nextProps.progress, maxProgress));
}
render() {
const progressViewStyle = {
width: this.state.progressValue,
backgroundColor: progressColor,
borderRadius:ProgressButton.isAndroid? innerRadius : 0
};
return (
<View style={progressViewWrapperStyle}>
<Animated.View style={progressViewStyle}/>
</View>
);
}
}