react-native - 我应该在 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 团队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
}...
]
推荐阅读
- reactjs - 在 chrome 开发者控制台中显示文件名而不是块
- java - 在二叉搜索树的数组实现上实现插入函数
- r - 如何过滤一个范围,而不仅仅是在
- shell - fslreorient2std 找不到图像
- robotframework - ROBOTFramework 最新版本(4.1) 兼容性问题
- google-oauth - Google Cloud Platform Web 应用程序配置更改传播延迟
- reactjs - 如何向 ReactDOM 显示 API 信息?
- iot - 如何让一个节点只偷听邻居的数据包而自己不发送或转发任何数据包?
- bash - 插入符号 + 大括号在 bash 变量中的作用是什么?
- amazon-web-services - 使用 for_each 的多个 aws_rds_cluster_instance