我在看Pluralsight关于React的课程,老师说道具不应该被改变。我现在正在读一篇关于道具vs.国家的文章(uberVU/react-guide),它说
道具和状态更改都会触发呈现更新。
文章后面说:
Props(属性的缩写)是组件的配置,如果可以的话,是它的选项。它们是从上面接收的,是不可变的。
所以道具可以改变,但它们应该是不可变的?
什么时候应该使用道具,什么时候应该使用状态?
如果你有一个React组件需要的数据,它应该通过道具或设置在React组件通过getInitialState?
Props: Props只是组件的属性,react组件只是一个javascript函数。
class Welcome extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
Const元素=;
这里<Welcome name="Sara" />传递一个对象{name: 'Sara'}作为Welcome组件的道具。为了将数据从一个父组件传递给子组件,我们使用props。
道具是不可变的。在组件的生命周期中,道具不应该改变(认为它们是不可变的)。
状态:状态只能在组件中访问。为了跟踪组件中的数据,我们使用状态。我们可以通过setState来改变状态。如果我们需要将state传递给child,我们必须将它作为props传递。
class Button extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
}
你可以通过将它与Plain联系起来来更好地理解它
JS函数。
简单地说,
State是组件的本地状态,不能在组件外部访问和修改。它相当于函数中的局部变量。
普通JS函数
const DummyFunction = () => {
let name = 'Manoj';
console.log(`Hey ${name}`)
}
反应组件
class DummyComponent extends React.Component {
state = {
name: 'Manoj'
}
render() {
return <div>Hello {this.state.name}</div>;
}
另一方面,通过赋予组件以道具形式从父组件接收数据的能力,道具可以使组件可重用。它们等价于函数参数。
普通JS函数
const DummyFunction = (name) => {
console.log(`Hey ${name}`)
}
// when using the function
DummyFunction('Manoj');
DummyFunction('Ajay');
反应组件
class DummyComponent extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />
工作人员:Manoj Singh Negi
文章链接:解释了反应状态与道具