【问题标题】:How can I get my components state to update with React?如何使用 React 更新组件状态?
【发布时间】:2017-10-24 21:00:02
【问题描述】:

我有一个显示菜单 div 和主 div 的登录页面。此页面有两种状态

constructor(props) {
   super(props);
   this.state = {
        file: 'Main',
        menuFile: '',
   }
}

我挂载我的组件并设置 menuFile 状态

componentWillMount() {
   let test = 'menuMain';
   this.setState({
       menuFile: test
    });
}

我通过从这个页面调用它们来呈现菜单和主 div

return (
 <div>
   <div className="menu">
     <Menu handleFileChange={this.handleFileChange.bind(this)} menuFile={this.state.menuFile} handleMenuChange={this.handleMenuChange.bind(this)} />
   </div>
   <div className="fileDiv">
      <File name={this.state.file} />
   </div>
 </div>

当程序加载时,所有这些都可以正常工作。问题是当我点击一个新菜单时,handleMenuChange() 被调用,但没有任何反应。

handleMenuChange() {
  this.setState( {menuFile} );
}

ex. 
 menuFile = menuMain when the program starts.
 The program loads menuMain find.  When I click on a new menu, menuFile becomes the new menu name let's say...
 menuFile = menuOptions
 If I console log menuFile it reads 'menuOptions', but the menuOptions menu isn't rendered to screen.  
 If I start the program with menuFile = menuOptions - -  then menuOptions is rendered out.  However, if I click on a menu button, the state is updated but the new menu isn't rendered out.

状态已更新为我希望将菜单更改为的 menuFile,但该菜单仍为默认菜单。无论出于何种原因,它都没有使用新状态调用并重新呈现新菜单。

如何查看状态更新以确保重新呈现页面?

我想应该是 shouldComponentUpdate() - 但我对如何使用它感到困惑。

【问题讨论】:

  • 把参数给你你的函数handleMenuChange(menuName),然后从Menu组件调用这个函数,参数像this.props.handleMenuChange('newName')。另外,如果您想要初始状态“menuMain”,为什么要将其放在 componentWillMount 中?您可以在构造函数中设置初始值并使用其他生命周期方法进行更改。

标签: reactjs components lifecycle


【解决方案1】:

正如我所见,menuFile 不是您的 Menu 容器的道具。你应该试试这个

handleMenuChange() {
   this.setState( {menuName: 'newName'} );
}

我看到的菜单取决于menuName

【讨论】:

  • 使用 this.props.handleMenuChange(menuString) 回调 ;其中 menuString 是 let menuString = 'newName' 例如
  • 顺便说一句,你写错了 this.handleMenuChagne
  • 如果我让 handleMenuChange() 使用 menuName: ' ' 代替,它仍然会收到新的状态名称,但菜单不会改变。我不知道为什么我可以在 componentWillMount() 中输入任何菜单名称并让它正确呈现,但是在程序运行时 - 单击菜单选项不会呈现新的菜单选项
  • 在渲染组件的过程中,我还是不明白你在哪里使用 this.state.menuFile
  • 更新了对 的调用 - 它应该是 menuFile={this.state.menuFile}
【解决方案2】:

你应该更新函数:

handleMenuChange() { this.setState( {menuFile} ); }

handleMenuChange(menuFile) { this.setState( {menuFile} ); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多