我面临的一个问题是,只有包装在div
中时,我的组件才会更新。
我有一个switch statement
来渲染孩子的不同版本。当我将第二种情况包装在div
中时,似乎一切正常,但是,如果不存在div
,则无法正常工作。似乎_getCurrentInputState
和selectedBlock
并没有更新。
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
中的内容,反应会发现它与众不同,并重新安装了所有内容。否则,它只会将其视为道具更改。
[没有看到EditorPanel
的实现,我无法再提供任何见解,但我想您未更改的道具只会在安装时设置一次,或类似的设置。
就像在映射元素时一样,您可以为开关中的每个元素提供key
,以通知反应每个元素都是唯一的。
switch (currentBlockType) {
case 'description': return (
<EditorPanel
key="description" // Add this
currentBlockType={'description'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
case 'skills_and_requirements': return (
<EditorPanel
key="skills_and_requirements" // Add this
currentBlockType={'skills_and_requirements'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
default: return (
<EditorPanel
key="default" // Add this
currentBlockType={'default'}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
第一件事,您根本不需要开关盒。其次,您将返回html,因此它是组件而不是方法,因此请以大写字母开头。您可以将代码减少为
const RenderEditorPanel = () => {
const currentBlockType = blockList[selectedBlock].type || 'default';
return (
<EditorPanel
currentBlockType={currentBlockType}
selectedBlock={selectedBlock}
_getBlock={_getBlock}
_getCurrentInputState={_getCurrentInputState}
_setCurrentInputState={_setCurrentInputState}
/>
)
}
此外,当我们使用此组件时,请像下面一样使用它
<RenderEditorPanel />
是的,所有组件都必须包装。如果您的JSX没有包装,反应将不快乐