Reactjs React钩子不更新状态
一些匹配数据是如何来自父类的,我使用useState(match)初始化了匹配 但是,matches数据包含旧数据,未更新为父匹配数据。有人帮忙吗Reactjs React钩子不更新状态,reactjs,react-hooks,Reactjs,React Hooks,一些匹配数据是如何来自父类的,我使用useState(match)初始化了匹配 但是,matches数据包含旧数据,未更新为父匹配数据。有人帮忙吗 const FixtureDetailItem = ({ type, match, teams, isAdmin, postMatchesStart, putMatchesStart }) => { console.log(match) const [matches, setMatches] = useState(match); c
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]);
在
useffect()
和useState
之间似乎有一个循环连接-useffect依赖于匹配项
,然后设置匹配项
如果希望它在match
更改时更改,那么match
应该是依赖项
请注意,useState(match)
仅在第一次渲染时激发。在后续渲染中,必须使用setMatches()
更改匹配项的值
constfixturedetailitem=({type,match,…})=>{
const[matches,setMatches]=useState(匹配);
常量{…}=匹配项;
useffect(()=>{
设置匹配(匹配)
},[匹配];
…//JSX在这里
}
@詹姆斯一世认为这可能需要一些澄清
请参见我上面的陈述-useState(match)仅在第一次渲染时激发
在第一次渲染时useState(match)
将匹配设置为等于match
然后父项更改match
,由于match属性更改,因此FixtureDetailItem
函数再次运行,但React不会针对新值(按设计)运行useState(match)
它认为匹配
是该组件的内部状态,并将其保留为旧值
由于匹配项
不会更改,因此效果不会运行-它只会在其中一个依赖项更改时运行。您做了错事。当更改匹配项时,效果将重新激发,因为匹配项是它的依赖项。也可以使用setMatches(matches)
而不是setMatches({…matches})
。如何实现内部状态以使用新值?一旦匹配被更改?使用setMatches()
-这就是useffect()
所做的。通过理解您所提到的“它将匹配视为此组件的内部状态,并将其保留为旧值”,上述代码似乎将内部匹配状态保留为旧值,因此子组件不会被更新。不是吗?没有setMatches()
可以更改它,但当然需要显式调用。