我正在使用Firebase进行用户身份验证,并且我想使用onAuthStateChanged()
来使用户在刷新浏览器后仍然存在。我还使用redux-sagas处理异步操作。
Index.jsx文件:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import './App.scss';
import store from './store';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
serviceWorker.unregister();
App.jsx:
import React, { Component } from 'react';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';
import { connect } from 'react-redux';
import Navbar from './components/navbar';
import routes from './routes';
import { actionTypes } from './components/signin/actionTypes';
const { VERIFY_REQUEST } = actionTypes;
const mapDispatchToProps = {
VERIFY_REQUEST,
};
class App extends Component {
render() {
return (
<Router>
<Navbar />
<Switch>
{routes.map(route => (
<Route
key={route.path}
path={route.path}
exact={route.exact}
component={route.component}
/>
))}
</Switch>
</Router>
);
}
}
export default connect(null, mapDispatchToProps)(App);
我的sagas生成器函数绑定到动作类型:
function onAuthState() {
return new Promise((resolve, reject) => {
loginToFirebase.auth().onAuthStateChanged(user => {
if (user) {
console.log(user);
resolve(user);
} else {
reject(new Error('Ops!'));
}
});
});
}
function* verifyUserAuth() {
try {
const LOGIN_API_URL = process.env.REACT_APP_USER_AUTH_API;
const { user } = yield onAuthState();
console.log(user);
const userInfo = { userAuth: user, userType: 'user' };
const config = { headers: { 'Content-Type': 'application/json' } };
const body = JSON.stringify(userInfo);
const response = yield axios.post(LOGIN_API_URL, body, config);
if (response.status === 200) {
const { data: { info } } = response.data;
yield put({ payload: info, type: VERIFY_SUCCESS });
} else yield put(loginError(response.status));
} catch (error) {
yield put(loginError(error));
}
}
export default function* watchUserLoginAction() {
yield takeEvery(VERIFY_REQUEST, verifyUserAuth);
}
每次我检查Redux工具时,都看不到组件安装上触发的操作。
答案 0 :(得分:1)
只要要在安装组件后 做某事,就可以使用componentDidMount
生命周期方法。修改您的mapDispatchToProps
const mapDispatchToProps = dispatch => {
return {
verifyRequest: () => { dispatch( {type : VERIFY_REQUEST} ) }
};
};
,然后从verifyRequest
呼叫componentDidMount
componentDidMount = () =>{
this.props.verifyRequest()
}
此外,最好创建动作创建者,而不是像这样直接分派动作
export const verifyRequestAction = () => {
return {
type: VERIFY_REQUEST
}
}
然后
const mapDispatchToProps = dispatch => {
return {
verifyRequest: () => { dispatch(verifyRequestAction()}
};
};