reactjs - 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]);
解决方案
之间似乎存在循环连接,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
没有改变,所以效果不会运行——它只在它的依赖项之一发生变化时运行。
推荐阅读
- c++ - 当我的类具有显式析构函数时,为什么 Valgrind 会给出不同数量的泄漏?
- react-native - redux 中的 action、reducer 和 store 有什么区别?
- android - 错误:包 R 不存在。我必须添加软件包吗?
- angularjs - 为什么有 ng-init 时 ng-model 会设置输入的值?
- java - 分块字段的默认值 - (setChunked)
- vb.net - 如何导入要在 VB.NET WebBrowser 中显示的 HTML 文件
- node.js - Express - POST 请求待处理
- ruby-on-rails - 如何在 Rails 上证明一个简单的控制器方法?
- css - 在 Bootstrap 中设计具有不同行的 2 列
- laravel - 没有选择类别不显示子类别