setState(...):即使安装了组件,也只能更新已安装或安装的组件

时间:2017-11-24 11:28:22

标签: javascript reactjs

我正在使用反应最新版本,点击运行expandMenu()

的按钮时收到以下错误

跟踪生命周期:

constructor
componentWillMount
render
componentDidMount
componentWillReceiveProps
render
componentWillReceiveProps
render
componentWillReceiveProps
render
expandMenu <<< click on the button - boom error!

运行expandMenu()时会挂载组件的AFAIK,这会使错误变得模糊不清。什么可能导致问题以及如何解决它?

  

setState(...):只能更新已安装或安装的组件。这个   通常意味着你在未安装的

上调用了setState()

export class Menu extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
	showPath: true,
	selectedItemIdx: 1,
    }
  }

  componentWillReceiveProps(nextProps: Props) {
    const { items } = nextProps
    this.setState({
      selectedItemIdx: items.length - 1,
    })
  }

  componentWillMount() {
    console.debug('componentWillMount')
  }

  componentDidMount() {
    console.debug('componentDidMount')
  }

  componentWillUnmount() {
    console.debug('componentWillUnmount')
  }

  expandMenu = () => {
    console.debug('expandMenu')
    const { items } = this.props
    if (items.length > 1) {
      this.setState({ showPath: true }) // error here
    }
  }

  itemClickHandler = (idx: number) => {
      this.expandMenu()
  }

  render() {
    console.debug('render')
    const { classes } = this.props
    return (
          <div className={classes.root}>
                <ButtonBase
                  className={classes.title}
                  onClick={() => {
                    this.itemClickHandler(idx)
                  }}
                >
              ))}
        
          </div>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

问题与react-hot-loader有关我必须将其从项目依赖项中删除。