Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State vs Props #6

Open
LiuL0703 opened this issue Jan 2, 2018 · 0 comments
Open

State vs Props #6

LiuL0703 opened this issue Jan 2, 2018 · 0 comments
Labels

Comments

@LiuL0703
Copy link
Owner

LiuL0703 commented Jan 2, 2018

props是一个父组件传递给子组件的数据流,这个数据流可以一直传递到子孙组件。而state代表的是一个组件内部自身的状态

条件 state props
能否从父组件获取初始值?
能否被父组件改变?
能否在组件内设置默认值? *
能否在组件内改变?
能否设置子组件的初始值?
能否在子组件中改变?

*:props 和 state 从父组件获取的初始值都会被在组件内设置的默认值覆盖。

If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.

如果一个组件在某个时间点需要改变自身的某个属性 那么这个属性应该用state 否则使用props

props
Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.

props(properties的简称)是一个组件的配置选项 它们从上而下被指定且不可变 一个组件不能改变自身的props 主要负责设置子组件的props props不仅仅可以作为数据传递也当做callback函数传递

state
The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

state是一种数据结构 当组件挂载是时state有一个默认值 它或许会随着时间的改变而变化 主要原因是用户事件触发
一个组件在内部管理自己的state 除了设置和初始化state 与其子组件state没有关系 可以认为state是一个组件的私有属性

何时使用:

State

如果component的某些状态需要被改变,并且会影响到component的render,那么这些状态就应该用state表示。
例如:一个购物车的component,会根据用户在购物车中添加的产品和产品数量,显示不同的价格,那么“总价”这个状态,就应该用state表示。

Props

如果component的某些状态由外部所决定,并且会影响到component的render,那么这些状态就应该用props表示。
例如:一个下拉菜单的component,有哪些菜单项,是由这个component的使用者和使用场景决定的,那么“菜单项”这个状态,就应该用props表示,并且由外部传入。

@LiuL0703 LiuL0703 added the React label Jan 2, 2018
@LiuL0703 LiuL0703 changed the title React中的state 和 props State vs Props Aug 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant