为啥不能根据道具反应设置初始状态

     2023-02-22     221

关键词:

【中文标题】为啥不能根据道具反应设置初始状态【英文标题】:Why cant react set initial state based on props为什么不能根据道具反应设置初始状态 【发布时间】:2018-10-28 10:40:42 【问题描述】:

我有一个 es6 react 组件,我希望 state 的初始值依赖于传递的 prop 的初始值,但它的值始终为 false:

AttachStateToProps 组件

<AttachStateToProps VALUE=false />

AttachStateToProps 组件:

class AttachStateToProps extends React.Component 
  state = 
    stateValue: this.props.VALUE,
  
  render() 
    console.log('Value of Prop - ', this.props.VALUE)
    console.log('Value of State - ', this.state.stateValue)

  return null
  

每次更改道具VALUE的值时,我都会得到:

`Value of Prop - false` // this changes whenever I change prop value in 
   <AttachStateToProps />

`Value of State - false` // this does not change accordingly.

我认为是 it could be something to do with state/setState being async 和更老的 getinitialState,但我不明白为什么。

【问题讨论】:

尝试改变componentDidMount中的状态 现在它一直返回true。 eslint 也抱怨 [eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state) - 我认为这不是一个好的模式 【参考方案1】:

从构造函数中的 props 初始化状态,或作为类属性,不会在 prop 更改时更新状态。但是,react 确实会检测到 prop 更改,并重新渲染组件。

示例:

class AttachStateToProps extends React.Component 
  state = 
    stateValue: this.props.VALUE,
  
  render() 
    console.log('Value of Prop - ', this.props.VALUE)
    console.log('Value of State - ', this.state.stateValue)

  return null
  


const renderWithVal = (val) => ReactDOM.render(
  <AttachStateToProps VALUE=val />,
  demo
);

renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

要在prop改变时更新状态,需要使用组件的lifecycle method。

使用 React ^16.3,您可以使用静态 getDerivedStateFromProps() 方法从 props 更新状态(并初始化它):

static getDerivedStateFromProps(nextProps)     
  return 
    stateValue: nextProps.VALUE,
  

class AttachStateToProps extends React.Component 
  state = ;

  static getDerivedStateFromProps(nextProps)     
    return 
      stateValue: nextProps.VALUE,
    
  
      
  render() 
    console.log('Value of Prop - ', this.props.VALUE)
    console.log('Value of State - ', this.state.stateValue)

  return null
  


const renderWithVal = (val) => ReactDOM.render(
  <AttachStateToProps VALUE=val />,
  demo
);

renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

对于 16.3 之前的 React 版本,您可以使用 componentWillReceiveProps()

注意:componentWillReceiveProps 已被弃用,但将在版本 17 之前有效。

componentWillReceiveProps(nextProps, prevState) 
  this.setState(
    stateValue: nextProps.VALUE,
  )

【讨论】:

【参考方案2】:

如果没有构造函数中的 super(props),它将无法工作。

    class AttachStateToProps extends React.Component  
constructor(props)  
super(props); 
this.state =  stateValue: this.props.VALUE, 
 
 
render()  
console.log('Value of Prop - ', this.props.VALUE) console.log('Value of State - ', this.state.stateValue) return null 

 

【讨论】:

反应自定义组件 - 无法根据道具设置状态

】反应自定义组件-无法根据道具设置状态【英文标题】:Reactcustomcomponent-can\'tsetstatebasedonprops【发布时间】:2019-12-2702:58:03【问题描述】:我必须将自定义日期选择器组件与内部状态绑定:this.state=selectedDate:null,dateText:"";到一个r... 查看详情

为啥在反应的“useState”钩子中一遍又一遍地设置初始状态

】为啥在反应的“useState”钩子中一遍又一遍地设置初始状态【英文标题】:Whyisinitialstatebeingsetoverandoveragaininthe"useState"hookofreact为什么在反应的“useState”钩子中一遍又一遍地设置初始状态【发布时间】:2021-04-2310:42:28【... 查看详情

更新道具时反应本机组件不透明度不更新

】更新道具时反应本机组件不透明度不更新【英文标题】:ReactNativecomponentopacitynotupdatingwhenpropsupdated【发布时间】:2018-06-2413:54:21【问题描述】:我有一个ReactNative子组件,如果disabled属性设置为true,它会将按钮呈现为半透明状... 查看详情

即使道具没有改变,为啥还要对重新渲染组件做出反应?

】即使道具没有改变,为啥还要对重新渲染组件做出反应?【英文标题】:Whyreactrerendrescomponentsevenifpropsdidn\'tchanged?即使道具没有改变,为什么还要对重新渲染组件做出反应?【发布时间】:2021-07-1617:59:18【问题描述】:我玩了... 查看详情

为啥我不能将此信息从一个反应组件推送到另一个?

】为啥我不能将此信息从一个反应组件推送到另一个?【英文标题】:Whycan\'tIpushthisinformationfromonereactcomponenttoanother?为什么我不能将此信息从一个反应组件推送到另一个?【发布时间】:2020-07-1622:06:15【问题描述】:仍然习惯Rea... 查看详情

为啥我不能在组件道具中使用内联函数?可以举个例子详细解释一下吗?失去所有状态是啥意思?

】为啥我不能在组件道具中使用内联函数?可以举个例子详细解释一下吗?失去所有状态是啥意思?【英文标题】:WhyIcannotuseinlinefunctionincomponentprop?Canyouexplainindetailbygivinganexample?Whatmeanssayinglosingallstate?为什么我不能在组件道具... 查看详情

ReactJs:在使用动态 Taglist 时使用道具设置初始状态

】ReactJs:在使用动态Taglist时使用道具设置初始状态【英文标题】:ReactJs:setinitialstateusingpropswhileusingdynamicTaglist【发布时间】:2017-11-2707:45:10【问题描述】:我正在发送一个名为tags的数组作为道具,我想将其分配为初始状态,以... 查看详情

使用 get API 调用反应全局状态/道具(没有 Redux)

】使用getAPI调用反应全局状态/道具(没有Redux)【英文标题】:Reactglobalstate/propswithgetAPIcalls(withoutRedux)【发布时间】:2018-05-0803:11:42【问题描述】:我有一个运行多个API调用的React组件。在初始加载时,会运行默认API调用。从默... 查看详情

Redux:如何将父道具传递到减速器的初始状态?

】Redux:如何将父道具传递到减速器的初始状态?【英文标题】:Redux:Howtopassparentpropsintotheinitialstateofareducer?【发布时间】:2018-01-1109:58:18【问题描述】:好吧,这让我很烦!在反应中,我有一个测试组件接收道具来创建其初始... 查看详情

根据道具值显示组件反应

】根据道具值显示组件反应【英文标题】:Displayingcomponentbasedonpropvaluereact【发布时间】:2020-10-0921:48:14【问题描述】:我有四个组件Rectangle、Circle、Triangle、Star。根据用户在道具中提供的值,我想返回组件。例如,如果用户将... 查看详情

是否可以仅在初始化道具时才渲染反应组件?

】是否可以仅在初始化道具时才渲染反应组件?【英文标题】:Isitpossibletorenderareactcomponentonlywhenapropisinitialized?【发布时间】:2020-07-0602:50:19【问题描述】:我正在尝试将道具search传递给我的AddressList组件。<divclassName="addresses"&... 查看详情

当提供者组件父状态发生变化时,为啥不能更新子组件中的值(带有反应上下文)?

】当提供者组件父状态发生变化时,为啥不能更新子组件中的值(带有反应上下文)?【英文标题】:Whycan\'tupdateavalueinachildcomponent(withreactcontext)whenaprovidercomponentparentstatechange?当提供者组件父状态发生变化时,为什么不能更新子... 查看详情

反应不通过道具将状态传递给孩子

】反应不通过道具将状态传递给孩子【英文标题】:Reactnotpassingstatetochildviaprops【发布时间】:2017-08-2217:41:18【问题描述】:我正在尝试将我的父级App状态传递给子组件Chart。应用constructor()super();this.state=dataPoints:\'424353\':date:\'10/1... 查看详情

向本机反应中的无状态组件发送道具

】向本机反应中的无状态组件发送道具【英文标题】:Sendingpropstostatelesscomponentsinreactnative【发布时间】:2017-07-1018:09:29【问题描述】:我正在尝试将图像源和标题作为道具发送到ReactNative中的定制无状态组件。(图片来源和标题... 查看详情

将所有状态和道具传递给孩子们反应

】将所有状态和道具传递给孩子们反应【英文标题】:passingtochildrenallstateandpropsinreact【发布时间】:2018-12-2508:09:54【问题描述】:我的渲染中有以下代码:<TourHeaderkey="TourHeader"...this.props,...this.state/>我收到以下错误:Syntaxerr... 查看详情

将 apss 道具或状态反应到子组件

】将apss道具或状态反应到子组件【英文标题】:reactapsspropsorstatetochildcomponent【发布时间】:2018-07-2422:36:34【问题描述】:我需要一些关于React组件的帮助。我是这方面的新手,我正在制作一个带有反应的网络应用程序,我想将... 查看详情

将新的商店状态放入道具后,反应不会重新渲染

】将新的商店状态放入道具后,反应不会重新渲染【英文标题】:reactdoesn\'tgetre-renderaftergettingnewstorestateintoprops【发布时间】:2019-12-0917:12:19【问题描述】:我正在使用react和react-redux。我使用mapstatetoprops和mapdispatchtoprops来更新我... 查看详情

从 Apollo 查询设置初始反应上下文状态

】从Apollo查询设置初始反应上下文状态【英文标题】:SettingInitialReactContextStatefromApolloQuery【发布时间】:2021-12-1418:32:08【问题描述】:我正在使用React.js,特别是Next.js,并且我有一个供用户使用的全局React上下文。上下文本身看... 查看详情