我有来自服务器的令牌身份验证,所以当我最初加载我的Redux应用程序时,我需要向此服务器发出请求以检查用户是否经过身份验证,如果是,我应该获得令牌。
我发现不建议使用Redux核心INIT操作,那么在呈现应用程序之前如何发送操作呢?
答案 0 :(得分:58)
您可以在根componentDidMount
方法中调度操作,在render
方法中可以验证身份验证状态。
这样的事情:
class App extends Component {
componentDidMount() {
this.props.getAuth()
}
render() {
return this.props.isReady
? <div> ready </div>
: <div>not ready</div>
}
}
const mapStateToProps = (state) => ({
isReady: state.isReady,
})
const mapDispatchToProps = {
getAuth,
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
答案 1 :(得分:24)
我对任何为此提出的解决方案都不满意,然后我想到我正在考虑需要渲染的类。如果我刚刚为启动创建了一个类,然后将内容推送到componentDidMount
方法并让render
显示加载屏幕呢?
<Provider store={store}>
<Startup>
<Router>
<Switch>
<Route exact path='/' component={Homepage} />
</Switch>
</Router>
</Startup>
</Provider>
然后有这样的事情:
class Startup extends Component {
static propTypes = {
connection: PropTypes.object
}
componentDidMount() {
this.props.actions.initialiseConnection();
}
render() {
return this.props.connection
? this.props.children
: (<p>Loading...</p>);
}
}
function mapStateToProps(state) {
return {
connection: state.connection
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Startup);
然后编写一些redux操作以异步初始化您的应用程序。是一种享受。
答案 2 :(得分:8)
更新:此答案适用于 React Router 3
我使用react-router onEnter道具解决了这个问题。这就是代码的样子:
// this function is called only once, before application initially starts to render react-route and any of its related DOM elements
// it can be used to add init config settings to the application
function onAppInit(dispatch) {
return (nextState, replace, callback) => {
dispatch(performTokenRequest())
.then(() => {
// callback is like a "next" function, app initialization is stopped until it is called.
callback();
});
};
}
const App = () => (
<Provider store={store}>
<IntlProvider locale={language} messages={messages}>
<div>
<Router history={history}>
<Route path="/" component={MainLayout} onEnter={onAppInit(store.dispatch)}>
<IndexRoute component={HomePage} />
<Route path="about" component={AboutPage} />
</Route>
</Router>
</div>
</IntlProvider>
</Provider>
);
答案 3 :(得分:2)
如果您使用的是React Hooks,一种解决方案是:
useEffect(() => store.dispatch(handleAppInit()), []);
空数组将确保在第一次渲染时仅调用一次。
完整示例:
import React, { useEffect } from 'react';
import { Provider } from 'react-redux';
import AppInitActions from './store/actions/appInit';
function App() {
useEffect(() => store.dispatch(AppInitActions.handleAppInit()), []);
return (
<Provider store={store}>
<div>
Hello World
</div>
</Provider>
);
}
export default App;
答案 4 :(得分:1)
类似,但是上面的替代方案(这似乎只适用于React-Router v3):
<强> Routes.js 强>
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from '../components/App';
import Home from '../views/Home';
import OnLoadAuth from '../containers/app/OnLoadAuth';
export default = (
<Route path="/" component={OnLoadAuth(App)}>
<IndexRoute component={Home} />
{* Routes that require authentication *}
</Route>
);
<强> OnLoadAuth.js 强>
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { authenticateUser, fetchingUser } from '../../actions/AuthActionCreators';
import Spinner from '../../components/loaders/Spinner';
export default App => {
class OnLoadAuth extends Component {
componentDidMount = () => this.props.authenticateUser();
render = () => (
(this.props.isLoading === undefined || this.props.isLoading)
? <Spinner />
: <App {...this.props} />
)
}
return connect(
state => ({ isLoading: state.auth.fetchingUser }),
{ authenticateUser, fetchingUser }
)(OnLoadAuth);
};
答案 5 :(得分:1)
以下是使用React(16.8)中最新版本的Hooks的答案:
import { appPreInit } from '../store/actions';
// app preInit is an action: const appPreInit = () => ({ type: APP_PRE_INIT })
import { useDispatch } from 'react-redux';
export default App() {
const dispatch = useDispatch();
// only change the dispatch effect when dispatch has changed, which should be never
useEffect(() => dispatch(appPreInit()), [ dispatch ]);
return (<div>---your app here---</div>);
}
答案 6 :(得分:0)
这里所有的答案似乎都是关于创建根组件并在componentDidMount中触发它的变体。我最喜欢redux的一件事是,它使数据获取与组件生命周期脱钩。我认为没有理由在这种情况下应该有所不同。
如果要将商店导入到根index.js
文件中,则可以在该文件中调度动作创建者(我们将其命名为initScript()
),它将在加载任何内容之前触发。
例如:
//index.js
store.dispatch(initScript());
ReactDOM.render(
<Provider store={store}>
<Routes />
</Provider>,
document.getElementById('root')
);
答案 7 :(得分:0)
使用redux-saga中间件,您可以轻松完成。
只需定义一个传奇,该传奇就不会在触发之前监视已调度的动作(例如,使用take
或takeLatest
)。像这样从根源fork
开始运行时,它将在应用启动时恰好运行一次。
以下是一个不完整的示例,它需要对redux-saga
包有一点了解,但可以说明这一点:
sagas / launchSaga.js
import { call, put } from 'redux-saga/effects';
import { launchStart, launchComplete } from '../actions/launch';
import { authenticationSuccess } from '../actions/authentication';
import { getAuthData } from '../utils/authentication';
// ... imports of other actions/functions etc..
/**
* Place for initial configurations to run once when the app starts.
*/
const launchSaga = function* launchSaga() {
yield put(launchStart());
// Your authentication handling can go here.
const authData = yield call(getAuthData, { params: ... });
// ... some more authentication logic
yield put(authenticationSuccess(authData)); // dispatch an action to notify the redux store of your authentication result
yield put(launchComplete());
};
export default [launchSaga];
上面的代码调度了您应创建的launchStart
和launchComplete
还原动作。最好创建这样的动作,以便在发射开始或完成时通知国家做其他事情。
然后,您的根传奇应该对此launchSaga
传奇进行分叉:
sagas / index.js
import { fork, all } from 'redux-saga/effects';
import launchSaga from './launchSaga';
// ... other saga imports
// Single entry point to start all sagas at once
const root = function* rootSaga() {
yield all([
fork( ... )
// ... other sagas
fork(launchSaga)
]);
};
export default root;
请阅读非常好的documentation of redux-saga,以获取有关它的更多信息。
答案 8 :(得分:0)
我正在使用redux-thunk从应用程序init的API端点获取用户下的帐户,并且它是异步的,因此数据在我的应用程序渲染后传入,并且上面的大多数解决方案都没有给我带来奇迹有些折旧了。所以我看了componentDidUpdate()。因此,基本上在APP初始化上,我必须具有API的帐户列表,并且我的redux存储帐户将为null或[]。此后求助于此。
class SwitchAccount extends Component {
constructor(props) {
super(props);
this.Format_Account_List = this.Format_Account_List.bind(this); //function to format list for html form drop down
//Local state
this.state = {
formattedUserAccounts : [], //Accounts list with html formatting for drop down
selectedUserAccount: [] //selected account by user
}
}
//Check if accounts has been updated by redux thunk and update state
componentDidUpdate(prevProps) {
if (prevProps.accounts !== this.props.accounts) {
this.Format_Account_List(this.props.accounts);
}
}
//take the JSON data and work with it :-)
Format_Account_List(json_data){
let a_users_list = []; //create user array
for(let i = 0; i < json_data.length; i++) {
let data = JSON.parse(json_data[i]);
let s_username = <option key={i} value={data.s_username}>{data.s_username}</option>;
a_users_list.push(s_username); //object
}
this.setState({formattedUserAccounts: a_users_list}); //state for drop down list (html formatted)
}
changeAccount() {
//do some account change checks here
}
render() {
return (
<Form >
<Form.Group >
<Form.Control onChange={e => this.setState( {selectedUserAccount : e.target.value})} as="select">
{this.state.formattedUserAccounts}
</Form.Control>
</Form.Group>
<Button variant="info" size="lg" onClick={this.changeAccount} block>Select</Button>
</Form>
);
}
}
const mapStateToProps = state => ({
accounts: state.accountSelection.accounts, //accounts from redux store
});
export default connect(mapStateToProps)(SwitchAccount);
答案 9 :(得分:0)
如果您使用的是React Hooks,则只需使用React.useEffect即可调度动作
React.useEffect(props.dispatchOnAuthListener, []);
我将这种模式用于注册onAuthStateChanged
侦听器
function App(props) {
const [user, setUser] = React.useState(props.authUser);
React.useEffect(() => setUser(props.authUser), [props.authUser]);
React.useEffect(props.dispatchOnAuthListener, []);
return <>{user.loading ? "Loading.." :"Hello! User"}<>;
}
const mapStateToProps = (state) => {
return {
authUser: state.authentication,
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatchOnAuthListener: () => dispatch(registerOnAuthListener()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
答案 10 :(得分:0)
与上面提到的 Chris Kemp 相同的解决方案。可以更通用,只是一个与 redux 无关的 canLift 函数?
interface Props {
selector: (state: RootState) => boolean;
loader?: JSX.Element;
}
const ReduxGate: React.FC<Props> = (props) => {
const canLiftGate = useAppSelector(props.selector);
return canLiftGate ? <>{props.children}</> : props.loader || <Loading />;
};
export default ReduxGate;
答案 11 :(得分:-1)
使用:Apollo Client 2.0,React-Router v4,React 16(光纤)
选择的答案使用旧的React Router v3。我需要“调度”来加载应用程序的全局设置。诀窍是使用componentWillUpdate,虽然示例是使用apollo客户端,而不是获取解决方案是等效的。
你不需要SettingsLoad.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from "redux";
import {
graphql,
compose,
} from 'react-apollo';
import {appSettingsLoad} from './actions/appActions';
import defQls from './defQls';
import {resolvePathObj} from "./utils/helper";
class SettingsLoad extends Component {
constructor(props) {
super(props);
}
componentWillMount() { // this give infinite loop or no sense if componente will mount or not, because render is called a lot of times
}
//componentWillReceiveProps(newProps) { // this give infinite loop
componentWillUpdate(newProps) {
const newrecord = resolvePathObj(newProps, 'getOrgSettings.getOrgSettings.record');
const oldrecord = resolvePathObj(this.props, 'getOrgSettings.getOrgSettings.record');
if (newrecord === oldrecord) {
// when oldrecord (undefined) !== newrecord (string), means ql is loaded, and this will happens
// one time, rest of time:
// oldrecord (undefined) == newrecord (undefined) // nothing loaded
// oldrecord (string) == newrecord (string) // ql loaded and present in props
return false;
}
if (typeof newrecord ==='undefined') {
return false;
}
// here will executed one time
setTimeout(() => {
this.props.appSettingsLoad( JSON.parse(this.props.getOrgSettings.getOrgSettings.record));
}, 1000);
}
componentDidMount() {
//console.log('did mount this props', this.props);
}
render() {
const record = resolvePathObj(this.props, 'getOrgSettings.getOrgSettings.record');
return record
? this.props.children
: (<p>...</p>);
}
}
const withGraphql = compose(
graphql(defQls.loadTable, {
name: 'loadTable',
options: props => {
const optionsValues = { };
optionsValues.fetchPolicy = 'network-only';
return optionsValues ;
},
}),
)(SettingsLoad);
const mapStateToProps = (state, ownProps) => {
return {
myState: state,
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators ({appSettingsLoad, dispatch }, dispatch ); // to set this.props.dispatch
};
const ComponentFull = connect(
mapStateToProps ,
mapDispatchToProps,
)(withGraphql);
export default ComponentFull;
App.js
class App extends Component<Props> {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store} >
<SettingsLoad>
<BrowserRouter>
<Switch>
<LayoutContainer
t={t}
i18n={i18n}
path="/myaccount"
component={MyAccount}
title="form.myAccount"
/>
<LayoutContainer
t={t}
i18n={i18n}
path="/dashboard"
component={Dashboard}
title="menu.dashboard"
/>