【问题标题】:React-hooks does not update stateReact-hooks 不更新状态
【发布时间】:2023-03-16 18:45:01
【问题描述】:

一些匹配数据来自父类,我使用 useState(match) 初始化匹配 但是,匹配数据包含旧数据,并未更新为父匹配数据。有人帮忙吗?

const FixtureDetailItem = ({ type, match, teams, isAdmin, postMatchesStart, putMatchesStart }) => {
  console.log(match)
  const [matches, setMatches] = useState(match);
  const { homeTeamId, homeTeamName, homeScore, awayTeamId, awayTeamName, awayScore, scheduledAt, location, league, matchRecords} = matches;

  useEffect(() => {
    console.log('fired')
    console.log(matches)
    setMatches(matches)
  }, [matches]);

【问题讨论】:

  • 你做错了什么。当匹配项改变时,效果会重新触发,因为匹配项是它的依赖项。
  • 也可以用setMatches(matches)代替setMatches({ ...matches })

标签: reactjs react-hooks


【解决方案1】:

useEffect()useState 之间似乎存在循环连接 - useEffect 具有 matches 的依赖关系,然后设置匹配项。

如果您希望它在match 更改时更改,那么match 应该是依赖项。

请注意,useState(match) 仅在第一次渲染时触发。在后续渲染中,您必须使用setMatches() 来更改matches 的值。

const FixtureDetailItem = ({ type, match, ... }) => {

  const [matches, setMatches] = useState(match);
  const { ... } = matches;

  useEffect(() => {
    setMatches(match)
  }, [match]);

  ... // JSX here

}

@James 我虽然这可能需要澄清一下。

请参阅我上面的声明 - useState(match) 仅在第一次渲染时触发

在第一次渲染时,useState(match) 设置 matches 等于 match

然后父级更改match,并且由于匹配属性更改,FixtureDetailItem 函数再次运行,但 React 不会为新值运行 useState(match)(按设计)。

它认为matches 是该组件的内部状态,并将其保留为旧值。

由于matches 没有改变,所以效果不会运行——它只会在它的依赖项之一发生变化时运行。

【讨论】:

  • 如何实现内部状态来使用新值?一旦匹配改变?
  • 使用setMatches() - 这就是useEffect() 正在做的事情。
  • 通过理解你提到的“它认为匹配是该组件的内部状态并保留旧值”上面的代码似乎将内部匹配状态保留为旧值,因此子组件是没更新。不是吗?
  • 没有setMatches()可以改变它,但当然需要显式调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2020-01-16
  • 2020-12-28
  • 1970-01-01
  • 2021-07-27
  • 2021-11-13
相关资源
最近更新 更多