【发布时间】:2021-04-26 17:40:58
【问题描述】:
如果状态改变,React 会重新渲染。那为什么下面的情况不能重新渲染呢?
根据程序行为,我发现
- 当状态改变时,如果该状态直接在组件中使用,会重新渲染。
- 当状态发生变化时,如果状态被用作子组件中的道具,它不会被重新渲染。
- 如何直接重新渲染该子组件?
以下程序来自我的代码并进行了一些修改。 更新: SandBox 这是我在沙盒中创建的代码,我尝试模拟我的真实情况
function List(props) {
const [fullListValue, setFullListValue] = useState([]); //store data which get from server
const [dropDrowList, setDropDrowList] = useState([]); //store data column value (e.g. data contain "fruit" column, this state will store "apple", "berry", "banana" etc.)
const setAllList = (data) => {
setFullListValue(data);
};
useEffect ( ()=> {
//axios call server, use setAllList(data) to save state
,[]}
//when fullListValue is updated,
useEffect(() => {
const dropDrowListCopy = [{ ['label']: 'ALL', ['value']: 'ALL' }];
//push all "fruit" data in dropDrowListCopy without duplicate
console.log(dropDrowListCopy); //this will show all dropdown I want, i.e. "ALL","apple", "berry", "banana"
setDropDrowList(dropDrowListCopy); //set to dropDrowList, and I expect this step will re-render the SelectionList component, however, it do not
}, [fullListValue]);
return (
<div>
<div>
{dropDrowList.length <= 1 ? (
'loading' //I add this to re-render the component, but I think this is not a good way to re-render the component
) : (
<SelectionList
itemList={dropDrowList}
/>
)}
</div>
</div>
);
}
【问题讨论】:
-
请在Minimal, Complete, and Reproducible 代码示例中包含所有相关代码。你能分享
SectionList代码吗?也许还有一个更准确的例子来说明你如何更新状态。 -
codesandbox.io/s/0wff7 这是我在沙箱中创建的代码,我尝试模拟我的真实情况
标签: reactjs components state