我在看Pluralsight关于React的课程,老师说道具不应该被改变。我现在正在读一篇关于道具vs.国家的文章(uberVU/react-guide),它说
道具和状态更改都会触发呈现更新。
文章后面说:
Props(属性的缩写)是组件的配置,如果可以的话,是它的选项。它们是从上面接收的,是不可变的。
所以道具可以改变,但它们应该是不可变的?
什么时候应该使用道具,什么时候应该使用状态?
如果你有一个React组件需要的数据,它应该通过道具或设置在React组件通过getInitialState?
一般来说,一个组件(父组件)的状态是子组件的prop。
State resides within a component where as props are passed from parent to
child.
Props are generally immutable.
class Parent extends React.Component {
constructor() {
super();
this.state = {
name : "John",
}
}
render() {
return (
<Child name={this.state.name}>
)
}
}
class Child extends React.Component {
constructor() {
super();
}
render() {
return(
{this.props.name}
)
}
}
在上面的代码中,我们有一个父类(parent),它的状态是name,它被传递给子组件(子类)作为道具,子组件使用{this.props.name}渲染它。
道具和状态之间的关键区别在于,状态是内部的,由组件本身控制,而道具是外部的,由呈现组件的任何东西控制。
function A(props) {
return <h1>{props.message}</h1>
}
render(<A message=”hello” />,document.getElementById(“root”));
class A extends React.Component{
constructor(props) {
super(props)
this.state={data:"Sample Data"}
}
render() {
return(<h2>Class State data: {this.state.data}</h2>)
}
}
render(<A />, document.getElementById("root"));
状态可以改变(可变的)
而道具不能(不可变)