我在看Pluralsight关于React的课程,老师说道具不应该被改变。我现在正在读一篇关于道具vs.国家的文章(uberVU/react-guide),它说
道具和状态更改都会触发呈现更新。
文章后面说:
Props(属性的缩写)是组件的配置,如果可以的话,是它的选项。它们是从上面接收的,是不可变的。
所以道具可以改变,但它们应该是不可变的?
什么时候应该使用道具,什么时候应该使用状态?
如果你有一个React组件需要的数据,它应该通过道具或设置在React组件通过getInitialState?
摘自:Andrea Chiarelli的书《开始React:用React简化前端开发工作流,增强应用程序的用户体验》:
Every React component has a props property. The purpose of this property is to collect data input passed to the component itself. JSX attribute is attached to a React element, a property with the same name is attached to the props object. So, we can access the passed data by using the attached property. In addition, the immutability of props allows us to think of components as pure functions, which are functions that have no side effects (since they don't change their input data). We can think of data passing from one component to another as a unidirectional data flow, from the parent component toward the child components. This gives us a more controllable system.
React provides a mechanism to support the automatic rendering of a component when data changes. Such a mechanism is based on the concept of state. React state is a property that represents data that changes over time. Every component supports the state property, but it should be used carefully. Components that store data that can change over time are said to be stateful components. A stateful component stores the state in the this.state property. To inform a component that the state has changed, you must use the setState() method. State initialization is the only case where you can assign a value to the this.state property without using setState().
setState()将新数据与已包含在状态中的旧数据合并,并覆盖先前的状态
setState()会触发render()方法的执行,所以永远不要显式地调用render()
你可以通过将它与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
文章链接:解释了反应状态与道具