如何用 React 替换组件的状态?

How can I replace component's state with react?

我在 MenuItemContainer

的组件中有一个本地状态 currentMenu
export default class MenuItemsContainer extends React.Component {
 constructor () {
  super();
  this.state = {
  currentMenu: [],
  };
}

我使用如下函数_renderMenuItem渲染menu_items

_renderMenuItems(menuitems) {
    const { order } = this.props;

    return menuitems.map((menuitem) => {
        if (menuitem.category_id == this.props.order.currentCategoryId) {
                this.state.currentMenu.push(menuitem)

        else {
            return false;
        }

        return <MenuItem
                key={menuitem.id}
                order={order}
                dispatch={this.props.dispatch}
                channel={this.props.order.channel}
                {...menuitem} />;
    });
}

我想用 currentMenu 做的是存储 menuItems 其中 menuItemcategory_id 等于订单状态的 currentCategoryId

现在我正在使用 push(menuitem) 将这些项目推送到状态。但是,在 currentMenu 中,仅当 menuItem 的 category_id 等于订单状态的 currentCategoryId 时才应存储。所以当 currentCategoryId 有变化时,它应该重置 currentMenu 并得到新的 menuItem

我该怎么做? 提前致谢

为了实际触发状态更改,您需要通过 setState 执行此操作 因此您可以在 _renderMenuItems 方法的末尾添加一个 setState 命令,如下所示:

this.setState({currentMenu: state.currentMenu})

但更好的做法是让状态已经包含正确的项目,而不是在渲染方法中过滤它。

我不确定您的示例是如何获取菜单项的,但理论上您应该从中构建状态,然后调用 _renderMenuItems 方法(将使用该状态)