Mat*_*ins 181 javascript properties reactjs
在开始使用React.js之后,看起来似乎props
是静态的(从父组件传入),而state
基于事件的更改.但是,我在文档中注意到了一个引用componentWillReceiveProps
,具体包括这个例子:
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
Run Code Online (Sandbox Code Playgroud)
这似乎意味着属性可以根据对比nextProps
来改变组件this.props
.我错过了什么?道具是如何改变的,还是我误解了它被称为何处?
Val*_*éry 223
组件不能更新自己的道具,除非它们是数组或对象(即使可能是反模式,组件更新自己的道具),但可以更新其状态和其子项的道具.
例如,仪表板speed
在其状态中具有一个字段,并将其传递给显示此速度的Gauge子项.它的render
方法就是return <Gauge speed={this.state.speed} />
.当仪表板调用时this.setState({speed: this.state.speed + 1})
,将使用新值重新呈现Gauge speed
.
就在此之前,Gauge componentWillReceiveProps
被调用,因此Gauge有机会将新值与旧值进行比较.
Ali*_*avi 35
道具
React组件应使用props来存储可以更改的信息,但只能由不同的组件更改.
州
React组件应使用state来存储组件本身可以更改的信息.
Valéry已经提供了一个很好的例子.
如果 props 是数组,则更新它们的技巧:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: this.props.count
}
}
increment(){
console.log("this.props.count");
console.log(this.props.count);
let count = this.state.count
count.push("new element");
this.setState({ count: count})
}
render() {
return (
<View style={styles.container}>
<Text>{ this.state.count.length }</Text>
<Button
onPress={this.increment.bind(this)}
title={ "Increase" }
/>
</View>
);
}
}
Counter.defaultProps = {
count: []
}
export default Counter
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Run Code Online (Sandbox Code Playgroud)
小智 5
钩子发生了很多变化,例如componentWillReceiveProps
变成了useEffect
+ useRef
(如this other SO answer所示),但道具仍然是只读的,所以只有调用者方法应该更新它。
归档时间: |
|
查看次数: |
236194 次 |
最近记录: |