首页 > 解决方案 > React-hooks 不更新状态

问题描述

一些匹配数据来自父类,我使用 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]);

标签: reactjsreact-hooks

解决方案


之间似乎存在循环连接,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.

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

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

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


推荐阅读