首页 > 解决方案 > 我应该在 compoenentDidMount 中设置状态吗?

问题描述

我有 AppContainer,这是其他屏幕呈现在:

class AppContainer extends Component {

state= {
  Home: false
}

renderFooterTab = () => {
    return this.footerItems.map((tabBarItem, index) => {
      return (
        <GlobalFooterTab
          key={index}
          title={tabBarItem.title}
          selected={tabBarItem.selected}
        />
      );
    });
  };

render() {
    return (
      <Container>
        <StatusBar />
        {this.renderHeader(this.props)}
        <Content {...this.props} contentContainerStyle={{ flexGrow: 1 }}>
          {this.props.children}
        </Content>
        {this.renderFooter(this.props)}
      </Container>
    );

footerItems = [
    {
      screen: 'home',
      title: 'Home,
      selected: this.state.isHome
    }...
]
}

使用反应导航,我可以使用 this.props.navigation.state;

this.props.navigation.state当我得到值和时如何改变状态NOT render the page twice


我这样做了,状态发生了变化,但选项卡没有呈现:

 componentDidMount() {
    this.setState({
      isHome: false
    });
  }

标签: react-nativereact-navigation

解决方案


确实没有必要使用它,并且React 团队state不鼓励使用它(搜索“避免将道具复制到状态中”)。相反,只需继续使用道具。

const { routeName } = this.props.navigation.state;

footerItems = [
  {
    screen: 'home',
    title: 'Home,
    selected: routeName === 'Home'
  }...
]

如果你真的想,你可以像这样使用“派生状态”:

const { routeName } = this.props.navigation.state;
const isHome = routeName === 'Home';

...

footerItems = [
  {
    screen: 'home',
    title: 'Home,
    selected: isHome
  }...
]


推荐阅读