Reactjs 组件仅在包装为'div'时更新`
我面临的一个问题是,我的组件只有在封装在div中时才会得到更新 我有一个switch语句来呈现不同版本的子对象。当我将我的第二个案例包装到一个div中时,似乎一切都正常,但如果这个div不存在,它就不会像预期的那样正常工作。似乎_getCurrentInputState和selectedBlock没有按其应该的方式更新Reactjs 组件仅在包装为'div'时更新`,reactjs,components,react-hooks,Reactjs,Components,React Hooks,我面临的一个问题是,我的组件只有在封装在div中时才会得到更新 我有一个switch语句来呈现不同版本的子对象。当我将我的第二个案例包装到一个div中时,似乎一切都正常,但如果这个div不存在,它就不会像预期的那样正常工作。似乎_getCurrentInputState和selectedBlock没有按其应该的方式更新 const Parent= () => { {/* ... */} const _renderEditorPanel = () =>{
const Parent= () => {
{/* ... */}
const _renderEditorPanel = () =>{
const currentBlockType = blockList[selectedBlock].type
switch(currentBlockType){
case 'description': return (
<EditorPanel
currentBlockType={'description'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
case 'skills_and_requirements': return (
<div> {/* <<<<<<<<<<<<<<<<<<<<<<<< This is needed to really update the child?
*/}
<EditorPanel
currentBlockType={'skills_and_requirements'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
</div> {/* <<<< and this.*/}
);
default: return (
<EditorPanel
currentBlockType={'default'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
);
}
}
return (
<StyledJobEditor>
{_renderEditorPanel()}
<div className="preview_panel">
<div>
<button onClick={
() => setSelectedBlock("1")
}>1</button>
<button onClick={() => setSelectedBlock("2")}>2</button>
<button onClick={() => setSelectedBlock("0")}>0</button>
</div>
{/*
The sidebar will be an arraw of block. We should expect to use the .map function here.
*/}
</div>
</StyledJobEditor>
);
}
我相信您看到这一点的原因是react无法判断它应该挂载同一组件的新实例。通过将一个更改为包装在div中,react可以看到它的不同,并重新装载所有内容。否则,它只是将其视为道具更改 没有看到EditorPanel的实现,我无法给出更多的见解,但我猜您未更改的道具只在挂载或类似的东西上设置一次 就像映射元素一样,您可以为交换机中的每个元素提供一个键,以告知react每个元素都是唯一的 开关电流块类型{ 案例“描述”:返回 案例“技能和需求”:返回 默认值:返回
首先,您根本不需要切换大小写。第二,您返回的是html,因此它是一个组件而不是一个方法,所以请以大写字母开头方法名称。您可以将代码缩减为
const RenderEditorPanel = () => {
const currentBlockType = blockList[selectedBlock].type || 'default';
return (
<EditorPanel
currentBlockType={currentBlockType}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
}
同样,当我们使用这个组件时,它应该如下所示
<RenderEditorPanel />
这很管用!我知道这与react只部分渲染我的元素有关,但我可以想出如何强制移除所有内容。谢谢你的帮助!是的,react基本上是看到的-上次我渲染EditorPanel组件,这次我也应该渲染一个,我将假设它们是同一个组件并重用第一个实例。通过传递一个键,您可以更好地控制react如何解释呈现同一组件。当您添加div时,它们不再匹配,因此react不会再三考虑并装载一个新实例。嗨,Nayan,谢谢您的回复。实际上,我返回JSX,需要switch语句,因为我将堆栈多个c随着时间的推移,我更喜欢使用switch语句,以便代码保持干净。