我正在使用react、redux和firestore我试图将用户传递给一个组件,然后使用uid从firestore中提取一些数据。但由于未知的原因(对我来说(,我一开始总是没有定义,但在第二次渲染时,我得到了正确的数据。
App.js:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
};
}
async componentDidMount() {
const { setCurrentUser } = this.props;
this.unsubscribeFromAuth = await FB.auth.onAuthStateChanged((user) => {
console.log('User:', user);
if (user) {
this.setState({ user });
localStorage.setItem('user', user.uid);
} else {
this.setState({ user: null });
localStorage.removeItem('user');
}
setCurrentUser(user);
});
}
render() {
return (
<Router>
<div className='App'>
<Header />
<Routes>
<Route path='/' exact element={<Page/>} />
</Routes>
<Footer />
</div>
</Router>
);
}
}
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
用户操作
import { UserActionTypes } from "./user.types";
export const setCurrentUser = (user) => ({
type: UserActionTypes.SET_CURRENT_USER,
payload: user,
});
用户选择器:
import { createSelector } from "reselect";
const selectUser = (state) => state.user;
export const selectCurrentUser = createSelector([selectUser],(user) => .currentUser
页面:
const Page=({ currentUser }) => {
const [user, setUser] = useState([]);
const userDB = async (currentUser) => {
console.log('userDB START:', currentUser);
if (!currentUser) return;
const userUID = currentUser.currentUser.uid;
const ref = doc(firestore, 'users', userUID);
const data = await getDoc(ref);
const dataSet = await data.json();
if (data) {
//NOTE THAT I NEVER GET IN HERE
console.log('docSnap.data: ', data.data());
setUser(data.data());
} else {
console.log('No such document!');
}
};
useEffect(() => {
userDB();
}, []);
return ();
};
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
});
export default connect(mapStateToProps)(Page)
输出为:
userDB START:未定义的
提前感谢
useEffect(() => {
userDB(currentUser);
}, []);
如果mapStateToProps实际上是未定义的,就像你的标题所说的
<Route path='/' exact element={<Page currentUser={this.state.user} />} />
已解决!基于@timotgl,谢谢!
App.js:删除了本地存储,因为它没有使用。
页面:
const Page= ({ currentUser }) => {
const [user, setUser] = useState([]);
const userDB = async (currentUser) => {
if (!currentUser) return;
const userUID = currentUser.uid;
const ref = doc(firestore, 'users', userUID);
const data = await getDoc(ref);
const dataSet = await data;
if (dataSet) {
console.log('docSnap.data: ', dataSet.data());
setUser(dataSet.data());
} else {
console.log('No such document!');
}
};
//changes in useEffect
useEffect(() => {
setUser(userDB(currentUser));
}, [currentUser]);
return ();
};
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
});
export default connect(mapStateToProps)(Page);