当链接到一个子组件的数据发生变化时,React 正在更新两个子组件
React is updating both child component when data linked to one child is changing
我有 2 个组件
- 形状
- 视频
他们在 1 条路线 ./home
我有 ./home 路由的上下文
<Router>
<div >
<PContext>
<Route exact path="/" component={home} />
</PContext>
</div>
</Router>
现在家里有
...
function Home() {
useEffect( ()=>{
console.log('Rendered PDetect')
})
return (
<div>
<Video/>
<Shape/>
</div>
);
}
export default Home;
我在 Video child 中有功能(检测纵横比),它将更新 PContext 中变量的纵横比值,形状组件将使用该值并显示它。
...
const Shape = () => {
const { ratio } = useContext(PDataContext)
console.log("ratio",ratio)
useEffect( ()=>{
console.log('Rendered Shape')
})
return (
<span className="shape_circle" >1</span>
)
}
export default Shape
上下文文件是
...
export const PDataContext = createContext()
const PContext = ( props ) => {
const [ ratio , setSetRatio ] = useState([])
const gotRatio = r => {
setSetRatio(r[0].key)
}
return(<PoseDataContext.Provider value={{
gotRatio,
ratio}}>
{props.children}
</PoseDataContext.Provider>
)
}
export default PoseContext
我的问题是 Video child 使用 gotRatio 函数并更新比率值,形状组件使用比率值来显示它。但是当 gotRatio 函数更新时,它会重新渲染形状和视频组件,因此视频再次从 0 秒开始
所有消费者将在 ReactJS Doc
更新其预期
All consumers that are descendants of a Provider will re-render whenever the Provider’s value
prop changes. The propagation from Provider to its descendant consumers (including .contextType
and useContext
) is not subject to the shouldComponentUpdate
method, so the consumer is updated even when an ancestor component skips an update.
我有 2 个组件
- 形状
- 视频
他们在 1 条路线 ./home
我有 ./home 路由的上下文
<Router>
<div >
<PContext>
<Route exact path="/" component={home} />
</PContext>
</div>
</Router>
现在家里有
...
function Home() {
useEffect( ()=>{
console.log('Rendered PDetect')
})
return (
<div>
<Video/>
<Shape/>
</div>
);
}
export default Home;
我在 Video child 中有功能(检测纵横比),它将更新 PContext 中变量的纵横比值,形状组件将使用该值并显示它。
...
const Shape = () => {
const { ratio } = useContext(PDataContext)
console.log("ratio",ratio)
useEffect( ()=>{
console.log('Rendered Shape')
})
return (
<span className="shape_circle" >1</span>
)
}
export default Shape
上下文文件是
...
export const PDataContext = createContext()
const PContext = ( props ) => {
const [ ratio , setSetRatio ] = useState([])
const gotRatio = r => {
setSetRatio(r[0].key)
}
return(<PoseDataContext.Provider value={{
gotRatio,
ratio}}>
{props.children}
</PoseDataContext.Provider>
)
}
export default PoseContext
我的问题是 Video child 使用 gotRatio 函数并更新比率值,形状组件使用比率值来显示它。但是当 gotRatio 函数更新时,它会重新渲染形状和视频组件,因此视频再次从 0 秒开始
所有消费者将在 ReactJS Doc
更新其预期All consumers that are descendants of a Provider will re-render whenever the Provider’s
value
prop changes. The propagation from Provider to its descendant consumers (including.contextType
anduseContext
) is not subject to theshouldComponentUpdate
method, so the consumer is updated even when an ancestor component skips an update.