【问题标题】:React: Content of Drawer is not rendered on state change反应:抽屉的内容不会在状态更改时呈现
【发布时间】:2018-05-18 11:23:32
【问题描述】:

我在子组件中有一个 Material UI 的 Drawer 组件(不是持久的,仅在单击按钮时打开),我想在其中显示通知列表。通知从服务器加载并从父组件传递。

我可以验证数据是否在状态更改时更新,并且调用了下面的渲染方法。 .map() 方法也被正确调用。但是抽屉里的东西是空的。 它显然在使用一堆静态列表项时有效,但在使用基于列表的 map() 时无效。 我的猜测是,这与更新发生时未显示抽屉有关。但是应该可以将动态数据添加到抽屉中,对吧?我在这里想念什么?

非常感谢任何帮助。

render() {
    return (
        <Drawer>
            <List>
                {this.props.notifications.map((n, key) => {
                <ListItem key={key}>
                    <ListItemIcon>
                        <Info/>
                    </ListItemIcon>
                    <ListItemText inset primary={n.header} secondary={n.message}/>
                </ListItem>
                })}
            </List>
        </Drawer>
    );
}

【问题讨论】:

  • 你是否在父组件中修改notifications,然后将其作为props传递?
  • 是的,完全正确。在父级中,我从服务器加载它,然后将其传递给子级:

标签: reactjs material-ui


【解决方案1】:

所以当你传递道具时

 <NotificationList notifications={this.state.notifications}>

this.state.notifications 确实在父组件中被修改。一旦调用了父组件的渲染方法;它也渲染所有子组件。因此,子组件中的道具将保持最初呈现的状态,直到您按需提出要求。

要在子组件中进行修改,您可以使用 componentWillReceiveProps()

 componentWillReceiveProps(props){
   console.log(props.notifications) //this will get you modified bits.
   this.setState({notifications:props.notifications});
 }

在子组件的渲染中

{this.state.notifications.map((n, key) => {
                <ListItem key={key}>
                    <ListItemIcon>
                        <Info/>
                    </ListItemIcon>
                    <ListItemText inset primary={n.header} secondary={n.message}/>
                </ListItem>
 })}

还要确保在子组件状态下初始化 notifications

construction(props){
 super(props);

    this.state = {
     notifications : []
    }
}

【讨论】:

    【解决方案2】:

    谢谢,我尝试使用 componentWillReceiveProps() 并设置我的子组件的状态,但不幸的是它没有帮助。通知确实在子组件中得到了更新,但它仍然没有呈现新的 ListItems。

    但是,与此同时,我确实设法解决了它。至少这对我有用。所以这是我的解决方案以供将来参考。我不得不将映射提取到一个单独的函数中:

    const mapItem = (notifications) => {
        return notifications.map((n, key) => (
            <ListItem key={key}>
                <ListItemIcon>
                    <Info/>
                </ListItemIcon>
                <ListItemText inset primary={n.header} secondary={n.message}/>
            </ListItem>
        ));
    };
    

    然后在render方法中这样使用:

    render() {
        return (
            <Drawer>
                <List>
                    {mapItem(this.props.notifications)}
                </List>
            </Drawer>
        );
    }
    

    这行得通,但老实说,我不能说为什么。为什么它不反过来。似乎 List 在呈现之前需要一个 ListItems 的常量列表。因此,如果有人对这种行为有解释,我很乐意听到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2019-04-10
      • 2017-09-18
      • 2021-07-10
      相关资源
      最近更新 更多