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

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

文章后面说:

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

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


当前回答

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

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

其他回答

道具和状态是相关的。一个组件的状态通常会成为子组件的道具。道具在父元素的呈现方法中作为React.createElement()的第二个参数传递给子元素,如果您使用的是JSX,则是更熟悉的标记属性。

<MyChild name={this.state.childsName} />

父类的childsName的状态值变成子类的this.props.name。从子进程的角度来看,名称道具是不可变的。如果它需要改变,父进程只需要改变它的内部状态:

this.setState({ childsName: 'New name' });

React会把它传播给你的子程序。一个自然的后续问题是:如果子程序需要更改其名称道具怎么办?这通常是通过子事件和父回调完成的。子进程可能会公开一个名为onNameChanged的事件。然后父进程通过传递回调处理程序来订阅事件。

<MyChild name={this.state.childsName} onNameChanged={this.handleName} />

子进程将通过调用this.props将其请求的新名称作为参数传递给事件回调。onNameChanged('New name'),父进程将在事件处理程序中使用该名称来更新其状态。

handleName: function(newName) {
   this.setState({ childsName: newName });
}

Basically, props and state are two ways the component can know what and how to render. Which part of the application state belongs to state and which to some top-level store, is more related to your app design, than to how React works. The simplest way to decide, IMO, is to think, whether this particular piece of data is useful for application as a whole, or it's some local information. Also, it's important to not duplicate state, so if some piece of data can be calculated from props - it should calculated from props.

For example, let's say you have some dropdown control (which wraps standart HTML select for custom styling), which can a) select some value from list, and b) be opened or closed (i.e., the options list displayed or hidden). Now, let's say your app displays a list of items of some sort and your dropdown controls filter for list entries. Then, it would be best to pass active filter value as a prop, and keep opened/closed state local. Also, to make it functional, you would pass an onChange handler from parent component, which would be called inside dropdown element and send updated information (new selected filter) to the store immediately. On the other hand, opened/closed state can be kept inside dropdown component, because the rest of the application doesn't really care if the control is opened, until user actually changes it value.

下面的代码是不完全工作,它需要css和处理下拉单击/模糊/改变事件,但我想保持示例最小。希望这有助于理解其中的区别。

const _store = {
    items: [
    { id: 1, label: 'One' },
    { id: 2, label: 'Two' },
    { id: 3, label: 'Three', new: true },
    { id: 4, label: 'Four', new: true },
    { id: 5, label: 'Five', important: true },
    { id: 6, label: 'Six' },
    { id: 7, label: 'Seven', important: true },
    ],
  activeFilter: 'important',
  possibleFilters: [
    { key: 'all', label: 'All' },
    { key: 'new', label: 'New' },
    { key: 'important', label: 'Important' }
  ]
}

function getFilteredItems(items, filter) {
    switch (filter) {
    case 'all':
        return items;

    case 'new':
        return items.filter(function(item) { return Boolean(item.new); });

    case 'important':
        return items.filter(function(item) { return Boolean(item.important); });

    default:
        return items;
  }
}

const App = React.createClass({
  render: function() {
    return (
            <div>
            My list:

            <ItemList   items={this.props.listItems} />
          <div>
            <Dropdown 
              onFilterChange={function(e) {
                _store.activeFilter = e.currentTarget.value;
                console.log(_store); // in real life, some action would be dispatched here
              }}
              filterOptions={this.props.filterOptions}
              value={this.props.activeFilter}
              />
          </div>
        </div>
      );
  }
});

const ItemList = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.items.map(function(item) {
          return <div key={item.id}>{item.id}: {item.label}</div>;
        })}
      </div>
    );
  }
});

const Dropdown = React.createClass({
    getInitialState: function() {
    return {
        isOpen: false
    };
  },

  render: function() {
    return (
        <div>
            <select 
            className="hidden-select" 
          onChange={this.props.onFilterChange}
          value={this.props.value}>
            {this.props.filterOptions.map(function(option) {
            return <option value={option.key} key={option.key}>{option.label}</option>
          })}
        </select>

        <div className={'custom-select' + (this.state.isOpen ? ' open' : '')} onClick={this.onClick}>
            <div className="selected-value">{this.props.activeFilter}</div>
          {this.props.filterOptions.map(function(option) {
            return <div data-value={option.key} key={option.key}>{option.label}</div>
          })}
        </div>
      </div>
    );
  },

  onClick: function(e) {
    this.setState({
        isOpen: !this.state.isOpen
    });
  }
});

ReactDOM.render(
  <App 
    listItems={getFilteredItems(_store.items, _store.activeFilter)} 
    filterOptions={_store.possibleFilters}
    activeFilter={_store.activeFilter}
    />,
  document.getElementById('root')
);

道具和状态之间的关键区别在于,状态是内部的,由组件本身控制,而道具是外部的,由呈现组件的任何东西控制。

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"));

状态可以改变(可变的) 而道具不能(不可变)

简单的解释是: STATE是组件的局部状态,例如color = "blue"或animation=true等。用这个。setState更改组件的状态。 PROPS是组件如何相互通信(将数据从父组件发送给子组件)以及如何使组件可重用。

用户在应用程序的某个地方输入了一些数据。

在其中输入数据的组件应该在其状态中拥有该数据,因为它需要在数据输入期间操作和更改它 在应用程序的其他任何地方,数据都应该作为道具传递给所有其他组件

所以,是的,道具是在变化的,但它们是从“源头”改变的,然后简单地从那里向下流动。所以道具在接收它们的组件的上下文中是不可变的。

例如,在一个参考数据屏幕上,用户编辑一个供应商列表将在状态下管理它,然后会有一个操作,导致更新的数据保存在ReferenceDataState中,它可能比AppState低一级,然后这个供应商列表将作为道具传递给所有需要使用它的组件。