简体   繁体   English

何时使用状态和道具?

[英]When to use state and when props?

I am studying the principles of react. 我正在研究反应的原则。

According to some reviews, some people says is better to keep your component stateless, what does it mean? 根据一些评论,有些人说更好地保持你的组件无状态,这是什么意思?

But other people says, that if you need to update your component, then you should learn how to set your state to the proper state. 但是其他人说,如果你需要更新组件,那么你应该学习如何将状态设置为正确的状态。

I saw this.props / this.setProps and this.state / this.setState and I am confuse with that. 我看到this.props / this.setPropsthis.state / this.setState ,我对此感到困惑。

Something I am trying to figure is, how can I update a component by itself and not from a parent component? 我想要解决的问题是,如何更新组件本身而不是父组件? should I use props or state in this case? 我应该在这种情况下使用道具或陈述吗?

I already read some docs about props and state, what I don't have clear, is: when to use one or another ? 我已经阅读了一些关于道具和状态的文档,我不清楚的是:何时使用其中一个?

Props vs. state comes down to "who owns this data?" 道具与国家归结为“谁拥有这些数据?”

If data is managed by one component, but another component needs access to that data, you'd pass the data from the one component to the other component via props. 如果数据由一个组件管理,但另一个组件需要访问该数据,则您可以通过props将数据从一个组件传递到另一个组件。

If a component manages the data itself , it should use state and setState to manage it. 如果组件管理数据本身 ,它应该使用state和setState来管理它。

So the answer to 所以答案

how can I update a component by itself and not from a parent component? 如何更新组件本身而不是父组件? should I use props or state in this case? 我应该在这种情况下使用道具或陈述吗?

is to use state. 是使用国家。

Props should be considered immutable and should never be changed via mutation. 道具应该被认为是不可改变的,不应该通过突变来改变 setProps is only useful on a top-level component and generally should not be used at all. setProps仅适用于顶级组件,通常不应使用。 If a component passes another component a property, and the first component wants the second to be able to change it, it should also pass it a function property that the second component can call to ask the first component to update its state. 如果一个组件通过另一个组件的属性,以及第一组件希望第二要能够改变它,它应该通过它的功能属性,第二组分可以打电话问的第一个组件来更新其状态。 For example: 例如:

var ComponentA = React.createClass({
  getInitialState: function() {
    return { count: 0 };
  },

  render: function() {
    return <Clicker count={this.state.count} incrementCount={this.increment} />;
  },

  increment: function() {
    this.setState({count: this.state.count + 1});
  }
});

// Notice that Clicker is stateless! It's only job is to
// (1) render its `count` prop, and (2) call its
// `incrementCount` prop when the button is clicked.
var Clicker = React.createClass({
  render: function() {
    // clicker knows nothing about *how* to update the count
    // only that it got passed a function that will do it for it
    return (
      <div>
        Count: {this.props.count}
        <button onClick={this.props.incrementCount}>+1</button>
      </div>
    );
  }
});

(Working example: https://jsbin.com/rakate/edit?html,js,output ) (工作示例: https//jsbin.com/rakate/edit?html,js,output

For and object-oriented programming analogy, think of a class/object: state would be the properties you put on the class; 对于和面向对象的编程类比,想一个类/对象: state将是你放在类上的属性; the class is free to update those as it sees fit. 该课程可以根据自己的需要自由更新。 Props would be like arguments to methods; 道具就像方法的论据; you should never mutate arguments passed to you. 你永远不应该改变传递给你的参数。


Keeping a component "stateless" means that it doesn't have any state, and all its rendering is based on its props. 保持组件“无状态”意味着它没有任何状态,并且它的所有渲染都基于它的道具。 Of course, there has to be state somewhere or else your app won't do anything! 当然,必须在某个地方建立状态,否则你的应用程序将不会做任何事情! So this guideline is basically saying to keep as many components as possible stateless, and only manage the state in as few top-level components as possible. 因此,本指南基本上是要尽可能多地保留无状态组件 ,并且只在尽可能少的顶级组件中管理状态。

Keeping components stateless makes them easier to understand, reuse, and test. 保持组件无状态使其更易于理解,重用和测试。

See A brief interlude: props vs state in the React docs for more information. 有关详细信息,请参阅React文档中的简短插曲:props vs state

Use state when you know the variable value is going to affect the view. 当您知道变量值将影响视图时使用state。 This is particularly critical in react, because whenever the state variable changes there is a rerender(though this is optimized with the virtual DOM, you should minimize it if you can), but not when a prop is changed (You can force this, but not really needed). 这在反应中尤其重要,因为每当状态变量发生变化时都会有一个重新渲染(虽然这是使用虚拟DOM进行优化的,如果可以的话,你应该最小化它), 但是当一个道具被改变时(你可以强迫它,但是不是真的需要)。

You can use props for holding all other variables, which you think can be passed into the component during the component creation. 您可以使用props来保存所有其他变量,您认为这些变量可以在组件创建期间传递到组件中。

If you have want to make a multi-select dropdown called MyDropdown for example 例如,如果您想要创建一个名为MyDropdown的多选下拉列表

state = {
    show: true,
    selected:[],
    suggestions:this.props.suggestionArr.filter((i)=>{
        return this.state.suggestions.indexOf(i)<0;
    })
}

props={
   eventNamespace:'mydropdown',
   prefix : 'm_',
   suggestionArr:[],
   onItemSelect:aCallbackFn
}

As you can see, the objects in the state variable are going to affect the view some way or the other. 如您所见,状态变量中的对象将以某种方式影响视图。 The objects in the props are mostly objects which should remain the same throughout the component life cycle. 道具中的对象主要是在整个组件生命周期中应保持相同的对象。 So these objects can be callback functions, strings used to namespace events or other holders. 因此,这些对象可以是回调函数,用于命名空间事件的字符串或其他持有者。

So if you do want to update the component by itself , you need to have to look into how componentWillRecieveProps ,componentWillUpdate, componentDidUpdate and componentShouldUpdate works. 因此,如果您确实希望自己更新组件 ,则需要了解componentWillRecieveProps,componentWillUpdate,componentDidUpdate和componentShouldUpdate的工作原理。 More or less, this depends on the requirement and you can use these lifecycle methods to ensure that the rendering is within the component and not in the parent. 或多或少,这取决于需求,您可以使用这些生命周期方法来确保呈现在组件内而不在父组件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM