简体   繁体   English

React/Redux - 何时使用状态和道具/何时更改道具

[英]React/Redux - When to use state and props / when to change props

My current understanding of mapStateToProps() is to map the currently set Redux store to any prop you want set within a component.我目前对mapStateToProps()理解是将当前设置的 Redux 存储映射到您想要在组件中设置的任何道具。 I also know that props are variables that are passed to the component and state` within the component is just a concurrent group of variables that are being utilized.我也知道props are variables that are passed to the component and内的 state` 只是一组正在使用的并发变量。

What is confusing me is that I am seeing on many sites/docs that you should never change the props.. Surely mapStateToProps() is physically changing the components props and goes against this ethos?令我困惑的是,我在许多网站/文档上看到,您永远不应该更改道具。 mapStateToProps()确实在物理上改变了组件道具并违背了这种精神?

Here's a scenario, say we are wanting to show a loading symbol while some backend process is being run, I can create a dispatch that will set IS_LOADING= True , if I wanted to apply this value to show the loader in my component I would apply this to a prop loading in the component, however when the component first loads wouldn't it error on running mapStateToProps() as state.loading does not exist yet?这是一个场景,假设我们想要在运行某个后端进程时显示加载符号,我可以创建一个将设置IS_LOADING= True的调度,如果我想应用这个值来显示我将应用的组件中的加载器这是组件中的道具加载,但是当组件第一次加载时,它不会在运行 mapStateToProps() 时出错,因为 state.loading 还不存在?

What is confusing me is that I am seeing on many sites/docs that you should never change the props让我感到困惑的是,我在许多网站/文档上看到您永远不应该更改道具

That means you should not change props from inside component .这意味着您不应该从component 内部更改 props。 The idea is that parent creates props for the child.这个想法是父母为孩子创造道具。 If props change components rerenders.如果道具更改组件重新渲染。

however when the component first loads wouldn't it error on running mapStateToProps() as state.loading does not exist yet?但是,当组件第一次加载时,它在运行 mapStateToProps() 时不会出错,因为 state.loading 还不存在?

It should not happen if you configure your store properly.如果您正确配置商店,则不会发生这种情况。 Store is created on the top level, so when your child component initializes store is already present. Store 是在顶层创建的,因此当您的子组件初始化时,store 已经存在。 So you have to configure your initial state properly.所以你必须正确配置你的初始状态。 E. g.例如set initial isLoading value to false .将初始isLoading值设置为false

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

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