父组件状态更新后子组件不更新
问题描述
下面代码中,ComponentA中的list更新后,ComponentB中的list不更新
export function ComponentA() {
const [list, setList] = useState([]);
useEffect(() => {
setTimeout(() => setList([1, 2, 3, 4, 5]), 1000);
}, []);
if (list.length === 0) return null;
return (
<View>
<ComponentB list={list} />
</View>
);
}
export function ComponentB(props) {
return (
<View>
<View>ComponentB</View>
<View>list length: {props.list.length}</View>
</View>
);
}
ComponentB.defaultProps = { list: [] };
期望行为 代码执行后,应先显示
ComponentB
list length: 0
1秒后触发timeout,应显示
ComponentB
list length: 5
但现在一直显示
ComponentB
list length: 0
但如果将代码改为如下,则正常执行
export function ComponentA() {
const [list, setList] = useState([]);
useEffect(() => {
setTimeout(() => setList([1, 2, 3, 4, 5]), 1000);
}, []);
if (!list || list.length === 0) return null;
return (
<View>
<ComponentB list={list} />
</View>
);
}
或
export function ComponentA() {
const [list, setList] = useState([]);
useEffect(() => {
setTimeout(() => setList([1, 2, 3, 4, 5]), 1000);
}, []);
return list.length === 0 ? null : (
<View>
<ComponentB list={list} />
</View>
);
}
系统信息
Taro v1.2 及以上版本已添加
taro info命令,方便大家查看系统及依赖信息,运行该命令后将结果贴下面即可。
- 操作系统: [Windows 10]
- Taro 版本 [1.3.0.beta5]
- Node.js 版本 [e.g. v8.10.0]
- 报错平台 [weapp]
欢迎提交 Issue~
如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏
如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。
Good luck and happy coding~
@masteroy return null 的处理还有问题,先写三元表达式吧。
@Chen-jj 好的。还有想请教一下,一个子组件即使在父组件中控制不render,子组件还是会用defaultProps render出来吗?所以在子组件里还得多一层控制?
@masteroy 不会吧,自己写写 demo 咯
CC @yuche
Taro 3 return null 也能正确处理了