我在看Pluralsight关于React的课程,老师说道具不应该被改变。我现在正在读一篇关于道具vs.国家的文章(uberVU/react-guide),它说

道具和状态更改都会触发呈现更新。

文章后面说:

Props(属性的缩写)是组件的配置,如果可以的话,是它的选项。它们是从上面接收的,是不可变的。

所以道具可以改变,但它们应该是不可变的? 什么时候应该使用道具,什么时候应该使用状态? 如果你有一个React组件需要的数据,它应该通过道具或设置在React组件通过getInitialState?


当前回答

react中的state和props都用于将数据控制到组件中,通常props由父组件设置并传递给子组件,并且它们在整个组件中都是固定的。对于将要改变的数据,我们必须使用状态。道具是不可变的,而状态是可变的,如果你想改变道具,你可以从父组件做,然后传递给子组件。

其他回答

props (properties的缩写)和state都是简单的JavaScript 对象。而两者都持有影响输出的信息 渲染,他们在一个重要的方面是不同的:道具被传递到 组件(类似于函数参数),而状态为 在组件中管理(类似于在组件中声明的变量 功能)。

所以简单的状态仅限于你当前的组件,但道具可以传递给任何组件你希望…你可以将当前组件的状态作为道具传递给其他组件……

同样在React中,我们有无状态的组件,它们只有道具,没有内部状态……

下面的例子展示了它们如何在你的应用程序中工作:

父组件(全状态组件):

class SuperClock extends React.Component {

  constructor(props) {
    super(props);
    this.state = {name: "Alireza", date: new Date().toLocaleTimeString()};
  }

  render() {
    return (
      <div>
        <Clock name={this.state.name} date={this.state.date} />
      </div>
    );
  }
}

子组件(无状态组件):

const Clock = ({name}, {date}) => (
    <div>
      <h1>{`Hi ${name}`}.</h1>
      <h2>{`It is ${date}`}.</h2>
    </div>
);

在回答最初关于道具不可变的问题时,我们说它们在子组件中是不可变的,但在父组件中是可以改变的。

大多数时候,你的子组件是无状态的,这意味着它们代表了它的父组件给它的数据/信息。

另一方面,状态处理的是处理组件本身,状态可以在组件内部通过setState和useState钩子改变。

例如

class Parent extends Component{
  constructor(props){
    super(props);
    this.state = {
      fruit: 'apple'
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(){
    this.setState({fruit: 'mango'})
  }
  render(){
    return (
      <div>
      <Child  fruit={this.state.fruit} />
      <button onClick={this.handleChange}>Change state</button>
      </div>
    )
  }
}

当点击按钮时,父类将其状态从apple更改为mango,并将其状态作为道具传递给子组件。现在,没有状态的子组件根据父组件的状态显示不同的标题。

class Child extends Component{

  render(){
    return(
      <h1>I have received a prop {this.props.fruit}</h1>
    )
  }
}

所以在根级别上,道具是父进程与子进程的通信,而状态是描述父进程的情况等。

你可以通过将它与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

文章链接:解释了反应状态与道具

state -这是一个特殊的可变属性,保存组件数据。它在Componet挂载时具有默认值。

props -这是一个特殊的属性,本质上是不可变的,用于从父到子的值传递。props只是组件之间的通信通道,总是从顶部(父组件)移动到底部(子组件)。

下面是结合状态和道具的完整示例

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>state&props example</title>

        <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
        <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
        <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

      </head>
      <body>
      <div id="root"></div>
        <script type="text/babel">

            var TodoList = React.createClass({
                render(){
                    return <div className='tacos-list'>
                                {
                                    this.props.list.map( ( todo, index ) => {
                                    return <p key={ `taco-${ index }` }>{ todo }</p>;
                            })}
                            </div>;
                }
            });

            var Todo = React.createClass({
                getInitialState(){
                    return {
                        list : [ 'Banana', 'Apple', 'Beans' ]       
                    }
                },
                handleReverse(){
                    this.setState({list : this.state.list.reverse()});
                },
                render(){
                    return <div className='parent-component'>
                              <h3 onClick={this.handleReverse}>List of todo:</h3>
                              <TodoList list={ this.state.list }  />
                           </div>;
                }
            });

            ReactDOM.render(
                <Todo/>,
                document.getElementById('root')
            );

        </script>
      </body>
      </html>