【问题标题】:React state resets back to initial value after component is mounted安装组件后,React 状态重置为初始值
【发布时间】:2017-11-26 20:43:51
【问题描述】:

我的组件是一个包含主要和次要导航的标题。到目前为止,我只处理主要导航,它在网站的大部分区域之间进行选择。状态提升到主 Header 组件,而 UpperMenu 组件仅接收事件侦听器和活动链接 ID 作为道具。

问题在于,虽然状态更改正确进行,但在执行挂载时,状态会更改回初始值。这会导致 CSS 中的“闪烁”,这意味着视图被正确呈现,并且在片刻之后它会返回到被选择的初始链接。我不知道什么可能导致这种行为,并希望得到帮助。

Header.js:

import React from 'react';
import UpperMenu from './UpperMenu';
import TopHeader from './TopHeader';
import styles from './Header.css';

const sections = [ 
  ["/sec0","section0"],
  ["/sec1","section1"],
  ["/sec2","section2"]
];

class Header extends React.Component {

constructor(props){
  super(props);
  this.state = {section: 0,
                submenu: 0};
}
// HERE THE STATE IS SET CORRECTLY
onSectionClick(event){
  console.log(event.target.id);
  this.setState({section:event.target.id[8]},
                 function () {console.log(this.state);});
}

// HERE PROBLEMS OCCUR, STATE IS INITIAL
componentDidMount(){
  console.log(this.state);
}

render() {
    return ( 
      <header id={styles.header}>
        <TopHeader />
        <UpperMenu  sections={sections} 
                    activeSection={sections[this.state.section][1]} 
                    onSectionClick={this.onSectionClick.bind(this)}/>
      </header>
    );
  };
 }

 export default Header;

UpperMenu.js:

import React from 'react';
import styles from './UpperMenu.css';
import {Link} from 'react-router';

class UpperMenu extends React.Component{

  render(){
   var activeSection = this.props.activeSection;
   var onSectionClick = this.props.onSectionClick;
   var sectionIndex = -1;

   return(
     <div className={styles.mmenu}>
       <ul className={styles.normal}>
         {this.props.sections.map(function(section){
            sectionIndex++;
            return( 
              <li key={section[1]}
                  id={"section_" + sectionIndex}
                  className={(activeSection === section[1]) ? styles.active : ""}
                  onClick={onSectionClick}>
                  <a id={"section_" + sectionIndex + "_a"}
                     href={section[0]}>{section[1]}</a>
              </li>
           )})}
       </ul>
    </div>);
    }
   }

export default UpperMenu;

附:我已尝试调试生命周期以确定发生这种情况的时间点以及问题从 componentDidMount 开始。

【问题讨论】:

    标签: reactjs react-lifecycle


    【解决方案1】:

    这是因为当您点击链接时,页面会重新渲染,因此状态会重置为初始状态。

    您可以通过将a 标记更改为react-routerLink 来解决此问题(仍然想知道为什么要导入它并使用a 标记)。

    说明:

    1. 当您点击链接(a 标签)时,浏览器(不是React-Router)会将您引导至“mysite/sectionX”页面,就像普通的静态网站一样。
    2. 当浏览器重新渲染新页面时,所有组件的状态都处于初始状态。 React-Router 读取 URL 中的路由并将您路由到该部分的组件。

    如果您使用Linkreact-router(不是浏览器)将负责路由和更改 URL,只有被路由的组件会被重新渲染并保持状态。

    【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2023-01-27
    • 2019-07-20
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多