React 中的 state 和 props 有什么区别? [英] What is the difference between state and props in React?

查看:31
本文介绍了React 中的 state 和 props 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在观看关于 React 的 Pluralsight 课程,讲师表示不应更改道具.我现在正在阅读一篇文章 (uberVU/react-guide)关于道具与状态,它说

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says

道具和状态更改都会触发渲染更新.

Both props and state changes trigger a render update.

文章后面说:

Props(properties 的缩写)是一个组件的配置,如果可以的话,它的选项.它们是从上面接收的并且是不可变的.

Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.

  • 那么 props 可以改变,但它们应该是不可变的?
  • 什么时候应该使用 props,什么时候应该使用 state?
  • 如果你有一个 React 组件需要的数据,它应该通过 props 传递还是通过 getInitialState 在 React 组件中设置?
    • So props can change but they should be immutable?
    • When should you use props and when should you use state?
    • If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?
    • 推荐答案

      你可以通过将它与平原联系起来最好地理解它JS 函数.

      简单地说,

      State 是组件的本地状态,无法在组件外部访问和修改.相当于函数中的局部变量.

      State is the local state of the component which cannot be accessed and modified outside of the component. It's equivalent to local variables in a function.

      普通JS函数

      const DummyFunction = () => {
        let name = 'Manoj';
        console.log(`Hey ${name}`)
      }
      

      React 组件

      class DummyComponent extends React.Component {
        state = {
          name: 'Manoj'
        }
        render() {
          return <div>Hello {this.state.name}</div>;
        }
      

      Props 另一方面,通过让组件能够以 props 的形式从其父组件接收数据,从而使组件可重用.它们等价于函数参数.

      Props, on the other hand, make components reusable by giving components the ability to receive data from their parent component in the form of props. They are equivalent to function parameters.

      普通JS函数

      const DummyFunction = (name) => {
        console.log(`Hey ${name}`)
      }
      
      // when using the function
      DummyFunction('Manoj');
      DummyFunction('Ajay');
      

      React 组件

      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 State vs Props 解释

      这篇关于React 中的 state 和 props 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆