【发布时间】:2020-07-10 01:53:49
【问题描述】:
我想将数据从 App.js 传递到 React 中的另一个 .js 文件。 Atm,我正在从文件之间的本地存储中读取和写入,但这似乎效率低下。当App.js 组件安装时,我只想从本地存储中提取一次。这就是我目前正在做的事情。
App.js:
constructor(props) {
super(props);
this.state = {
user: {},
user_data: (localStorage.getItem('user_data')),
}
this.authListener = this.authListener.bind(this);
}
componentDidMount() {
this.authListener();
}
//checks firebase for authentication
authListener() {
Authentication.auth().onAuthStateChanged((user) => {
console.log(user);
if (user) {
this.setState({ user });
localStorage.setItem('user', user.uid);
this.pulldata_Health();
this.pulldata_Meals();
this.pulldata_Ingredients();
} else {
this.setState({ user: null })
localStorage.removeItem('user');
localStorage.removeItem('user_data')
}
});
}
//connects to database and stores data to local storage
pulldata_Health() {
database.collection('Health_data')
.doc(localStorage.getItem('user'))
.get()
.then(doc => {
const data = doc.data();
localStorage.setItem('user_data', JSON.stringify(data));
console.log(JSON.parse(localStorage.getItem('user_data')))
}).catch(function (error) {
console.error("Error reading health", error);
});
Homepage.js:
constructor(props) {
super(props);
this.state = {
healthData: (JSON.parse(localStorage.getItem('user_data')))
}
}
componentDidMount() {
this.GoalChecker();
console.log(this.state.healthData);
}
GoalChecker() {
if (this.state.healthData !== null) {
if (this.state.healthData.goal === 'Gain') {
this.setState({ gainImage: true });
this.setState({ recompImage: false });
this.setState({ loseImage: false });
console.log('gainimg')
}
if (this.state.healthData.goal === 'Recomp') {
this.setState({ gainImage: false });
this.setState({ recompImage: true });
this.setState({ loseImage: false });
console.log('recompimg')
}
if (this.state.healthData.goal === 'Lose') {
this.setState({ gainImage: false });
this.setState({ recompImage: false });
this.setState({ loseImage: true });
console.log('loseimg')
}
}
};
这一切都有效,但每次加载此页面时从本地存储中提取似乎有点低效。有什么办法可以将App.js的User数据的props推送到我的其他页面?
【问题讨论】:
-
使用全局状态或查看
redux
标签: html json reactjs dom local-storage