在阵营本地
问题描述:
嗨现有状态转移(如内`render`)期间无法更新我有一个屏幕,在这里我有isProductTourCompleted
如果真的话,我要前往Dashboard
屏幕的条件。我正在尝试使用AsyncStorage
API在componentDidMount
方法中获得它的价值。我也尝试在componentWillMount
更新它,但没有运气。在阵营本地
如果这是真的,则在更新状态,并重新呈现组件并导航到Dashboard
。它打开Dashboard
屏幕但显示此警告。
我检查了其它一些原因,几个线程。任何人都可以提示我我做错了什么?
现有状态转移(如
render
内)的阵营本地
export default class FirstProductTour extends Component {
constructor(props) {
super(props);
this._startDashboardScreen = this._startDashboardScreen.bind(this);
this.state = {
isProductTourCompleted: false
};
}
componentDidMount() {
AsyncStorage.getItem("@ProductTour:key").then(value => {
if (value)
this.setState({
isProductTourCompleted: true
});
});
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
{this.state.isProductTourCompleted
? this._startDashboardScreen()
: <View style={styles.container}>
<Image source={require("../../img/talk_people.png")} />
<Text style={styles.centerAlignTextStyle}>
{strings.talk_people}
</Text>
<RoundButton
robotoThinStyle={styles.roundButtonStyle}
centerAlignTextStyle={styles.whiteColorStyle}
onPress={() => {
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: "SecondProductTour"
})
]
});
this.props.navigation.dispatch(resetAction);
}}
>
{strings.continueText}
</RoundButton>
</View>}
</View>
);
}
_startDashboardScreen() {
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: "Dashboard"
})
]
});
this.props.navigation.dispatch(resetAction);
}
}
答
你需要检查是否导航到FirstProductTour或DashPage上时,无法更新功能或从一个单独的容器。
在内部,React使用多种巧妙的技术来最小化更新UI所需的昂贵DOM操作的数量。
在componentDidMount
设置的状态只会触发频繁的重新渲染,这会导致糟糕的性能优化。即使道具没有改变,组件也会重新渲染。
最佳解决方案:使用不标准检查和判定导航容器组件(或类似ButtonClick的函数)。
另一个解决方案将检查条件并调用componentwillMount
上的导航功能。像下面的东西
componentDidMount() {
AsyncStorage.getItem("@ProductTour:key").then(value => {
if (value)
this._startDashboardScreen()
});
}
你需要检查是否导航到FirstProductTour或DashPage函数或从一个单独的容器。你不能在渲染上检查它,因为这会导致错误。尝试调用ComponentDidMount上的导航而不是设置状态。 – Vicky
@vicky是正确的。如果productTourCompleted为true,则不会显示您正在更改状态/视图,因此如果您只想导航到不同的屏幕,则无需重新渲染。而不是你的ComponentDidMount中的setState,在那里调用你的导航。 – basudz
看起来像它的工作:) @Vicky你们可以用一些细节回答所以它会为未来的读者是太有用并接受它:) –