【发布时间】:2019-11-28 10:38:29
【问题描述】:
首先,感谢您阅读我的内容。我正在使用 Expo 进行本机反应。我使用 componentWillMount 和 componentDidMount 在我的应用程序中设置功能。 它可以正常工作,但是我很难理解为什么我的组件会渲染 4 次...
我得到了这个结果(使用我的 console.log):
结果检索设备制造商():42 ===>retrieveProfileUserId 42 结果retrieveDeviceUID() : ... 结果retrieveDeviceOSVersion() : 10 结果 retrieveDeviceManufacturer() :谷歌连接类型 wifi 是 连接的?真的
但是每次我执行该组件时连续 4 次。 我当然是 react-native 的新手,需要帮助才能完全理解这一点。
如果您能提供帮助,非常感谢。这是我的完整代码页:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { isFirstConnection: true };
status: "0";
deviceOSVersion: null;
deviceManufacturer: null;
deviceUID: null;
profileUserId: null;
}
performTimeConsumingTask = async () => {
return new Promise(resolve =>
setTimeout(() => {
resolve("result");
}, 1000)
);
};
componentWillMount = async () => {
this.setState({ deviceOSVersion: await retrieveDeviceOSVersion() });
this.setState({ deviceManufacturer: await retrieveDeviceManufacturer() });
this.setState({ deviceUID: await retrieveDeviceUID() });
this.setState({ profileUserId: await retrieveProfileUserId() });
};
async componentDidMount() {
this.setState({ status: "6" });
// Preload data from an external API
// Preload data using AsyncStorage
const data = await this.performTimeConsumingTask();
if (data !== null) {
this.setState({ isFirstConnection: false });
}
Font.loadAsync({
Roboto: require("./assets/fonts/Roboto-Black.ttf")
});
}
render() {
if (this.state.status == "6") {
console.log(
"Results retrieveDeviceManufacturer() : ",
this.state.profileUserId
);
if (this.state.profileUserId !== null && this.state.profileUserId > 0) {
// OK
} else {
// Need connection
}
console.log("===>retrieveProfileUserId", this.state.profileUserId);
// Device UUID
console.log("Results retrieveDeviceUID() : ", this.state.deviceUID);
if (this.state.deviceUID !== null) {
// OK
} else {
// TODO : next step...
storeDeviceUID(getDeviceUID());
}
// Detect Manufacturer : iOS, Android, ..
if (this.state.deviceManufacturer !== null) {
// OK
} else {
storeDeviceManufacturer(getDeviceManufacturer());
}
// Get system version
if (this.state.deviceOSVersion !== null) {
// OK
} else {
storeDeviceOSVersion(getDeviceOSVersion());
}
console.log(
"Results retrieveDeviceOSVersion() : ",
this.state.deviceOSVersion
);
console.log(
"Results retrieveDeviceManufacturer() : ",
this.state.deviceManufacturer
);
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
if (this.state.isFirstConnection) {
return <SplashScreen />;
}
return <Navigation />;
} else {
console.log("STATUS INITIALISATION");
this.setState({ status: "1" });
return null;
}
}
}
【问题讨论】:
标签: react-native expo react-lifecycle