【问题标题】:How to update component state on redux state change?如何在 redux 状态更改时更新组件状态?
【发布时间】:2018-05-21 14:03:32
【问题描述】:

由于我有一个带有表单的组件,我需要将表单连接到组件状态。初始数据来自 Redux,因此尝试通过使用 props 设置状态来初始化和更新组件:

componentWillMount = () => {
  this.setState({
    language: this.props.language || 'en'
  })
}

language 是一个已连接的道具,我检查了它是否在商店中更新。

const mapStateToProps = state => ({
  language: state.language
})

我也尝试使用componentWillReceiveProps 和componentWillUpdate,但它不起作用。我得到了初始状态,即使 store 和 connected props 发生了变化,组件的状态也不会更新。

{this.props.language} // updates
{this.state.language} // doesn't change

从 Redux 数据管理表单的正确方法是什么?


render 部分:

render () {
  const {classes, theme, web} = this.props

  const language = (
    <CardContent>
      <Typography type="headline">
        Language
      </Typography>
      <Divider/>
      <form className={classes.container} autoComplete="off">
        <FormControl fullWidth margin="normal">
          <InputLabel htmlFor="language">Select Block</InputLabel>
          <Select
            value={this.state.language} // <==================== language
            onChange={this.handleLanguaheChange}
            input={<Input id="language"/>}
          >
            <MenuItem value={'en'}>English</MenuItem>
            <MenuItem value={'he'}>עברית</MenuItem>
          </Select>
        </FormControl>
      </form>
    </CardContent>
  )
  ...

  return (
      <Grid
        container
        spacing={theme.spacing.unit * 3}
        justify={'space-between'}
        className={classes.gridWrap}
      >
        <Grid item xs={6}>
          <Card className={classes.card}>
            {language}
          </Card>
...

【问题讨论】:

  • 您是否在 componentWillReceiveProps 中设置状态。在componentWillMount中同步调用setState也不会触发额外的渲染
  • @ShubhamKhatri 我试过componentWillMount 、componentWillUpdate 和componentWillReceiveProps ,但都没有奏效
  • 能否添加你的componentWillReceiveProps的相关代码
  • @ShubhamKhatri 它与我粘贴的代码完全相同 componentWillMount
  • 处理程序上的错字:` onChange={this.handleLanguaheChange} `... 编辑模式不允许我修复,除非我再编辑 5 个字符????

标签: javascript forms reactjs redux react-redux


【解决方案1】:

首先,您为 componentWillMount 使用箭头函数。经验法则是,不要将箭头函数用于生命周期挂钩(componentWillMount、shouldComponentUpdate、...等)。通常在 componentWillMount 钩子中设置状态。但永远不要在 componentDidMount 中设置状态。 请尝试将其重写为,

constructor(props) {
 super(props)
 this.state = {
  language: 'en',
 }
}
componentWillMount() {
 const { language } = this.props
 if (language) this.setState(prevState => ({ language: prevState.language = language }))
}

在某些特殊情况下,例如我在一个 .js 文件中编写了两个类(就像我说的,有些例外)并且我无法按预期从 componentWillMount 修改它(后来注意到,props 已修改由子类)。 在这种情况下,您可以在渲染中覆盖它

render() {
 const { language } = this.props
 if (language) this.setState(prevState => ({ language: prevState.language = language }))

【讨论】:

  • 通常在 componentWillMount 挂钩中设置状态。但永远不要在 componentDidMount 中设置状态。 永远不要那样做。您不应该为未安装的组件设置状态,这可能会导致内存丢失。在 ComponentDidMount 中设置状态也没有问题。
【解决方案2】:

要使用 React Hooks 完成此操作:

  1. 使用useRef() 跟踪以前的值
  2. 与之前的值比较并有条件地更新本地组件状态

发布的示例对我来说真的没有意义,所以这是我面临的问题:

我有一个带有组件状态的表单,我需要在 redux 状态更改时清除它。

为了实现这一点,我的组件如下所示:

import { useSelector } from 'react-redux';
import React, { useState, useEffect, useRef } from 'react';
const CreateCase = () => {

  //redux state
  const accounts = useSelector(state => state.accounts);

  //component state
  const [productId, setProductId] = useState(undefined);

  const prevAccountRef = useRef<string>();
  useEffect(() => {
    //compare current with previous account and clear productId if changed
    if (account.id != prevAccountRef.current) {
      setProductId(undefined);
    }
    //set previous account for next render
    prevAccountRef.current = account.id;
  });

  //... render
}

您只能有条件地在useEffect 内运行setState,这一点非常重要。

【讨论】:

    【解决方案3】:

    即使 store 和 connected props 发生变化,组件的状态也不会更新

    按照您编写的方式,除非您使用setState()(很可能在componentWillReceiveProps() 方法中)显式更新它,否则状态不会更新。

    当您将 mapStateToProps() 与 Redux connect() HOC 一起使用时,您正在通过其 props 将您的 Redux 状态映射到您的组件,因此在您的情况下,this.props.language 将在 Redux 存储时更新更新。

    【讨论】:

    • 是的,所以我认为一旦道具更新,它会触发componentWillReceiveProps,从而更新状态。我错了吗?
    • 抱歉,当 react-redux 将 Redux 的 state 映射到 props 而不是组件的 @987654332 时,组件的 state(更新为 this.setState)的用途是什么@?那我们什么时候使用组件的state呢?
    • @tonix 我相信您想使用道具在外部更改状态,并使用状态在内部更改状态(与组件相关)。
    • @Kin 喜欢更改仅与组件相关而不是整个应用程序的内容。
    【解决方案4】:

    componentWillReceiveProps 只会在你的组件重新渲染时被调用。

    组件第一次挂载时,不会触发。

    你不能在componentwillupdate里面调用setState。

    为了从redux store初始化组件的初始状态,你应该使用constructor。

        constructor(props) {
    
        super(props);
    
        this.state = {
            language: this.props.language || 'en'
         }
       }
    

    【讨论】:

    • 谢谢,在这种情况下使用constructor 和componentwillMount/reciveProps 有什么区别?
    • 请分享您正在使用的渲染部分
    • @ilyo this.state.language 还在。构造函数更改后需要使用this.props.language
    • 我很困惑,设置状态的重点是(1)我可以将它与表单一起使用(2)我将有一个备用值,直到服务器填充 redux 存储
    【解决方案5】:

    不确定这是否适用,但我最近遇到了类似的问题,我的情况是由于调用 this.setState 并不能保证 即时 更新状态;它只是说状态更改最终会生效。

    来自 react-component 文档:

    将 setState() 视为请求而不是立即命令 更新组件。为了获得更好的感知性能,React 可能 延迟它,然后一次更新几个组件。反应 不保证立即应用状态更改。

    setState() 并不总是立即更新组件。有可能 批处理或推迟更新。这使得阅读 this.state 就在调用 setState() 之后,这是一个潜在的陷阱。相反,使用 componentDidUpdate 或 setState 回调(setState(updater, 回调)),其中任何一个都保证在更新后触发 已应用。如果需要根据前面的设置状态 状态,请阅读下面的更新程序参数。

    如果您需要对状态或依赖于状态的事物进行一些“即时”更改,那么您可以使用 setState() 上的回调将事物锁定到位。回调对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2021-08-11
      • 2019-12-29
      • 2020-05-01
      相关资源
      最近更新 更多