【发布时间】:2020-05-07 07:48:20
【问题描述】:
伙计们,我想转换此代码:
export default class App extends Component {
constructor(props) {
super(props);
this.state = { isLoading: true };
}
performTimeConsumingTask = async () => {
return new Promise((resolve) =>
setTimeout(() => {
resolve('result');
}, 2000)
);
};
async componentDidMount() {
const data = await this.performTimeConsumingTask();
if (data !== null) this.setState({ isLoading: false });
}
render() {
if (this.state.isLoading) return <SplashScreen />;
const { state, navigate } = this.props.navigation;
return (something)
我写了这段代码,但它不起作用:
const App = () => {
const [fontLoaded, setFontLoaded] = useState(false);
const [isTimerOn, setIsTimerOn] = useState(true);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setFontLoaded(true)}
/>
);
}
useEffect(async () => {
const data = await performTimeConsumingTask();
if (data !== null) setIsTimerOn(false);
});
if (isTimerOn) return <SplashScreen />;
else {
return (something)
这将显示一个错误:
Invariant Violation: Rendered More Hooks than during the previous render.
如果我评论 useEffect 钩子,它将运行 splashScreen。谁能帮我转换一下?
【问题讨论】:
标签: javascript react-native react-hooks