首先如何在redux中获取初始状态,然后可以在我的组件方法中使用它?

时间:2018-11-09 22:39:48

标签: reactjs redux

我正在将React.js与redux一起使用来构建我的项目。 目前,我以全局状态存储用户的令牌。但是如何在每个组件安装之前获取令牌?例如。我在axios action中有一个redux,可以从ComponentDidMount中的REST API中获取数据:

现在,此方法将陷入ComponenDidMount,因为它无法获取令牌(令牌最初为null,并存储在另一个reducer中)。

  componentDidMount() {
       this.props.loadProfile()
      }


// in actions
export const loadProfile = (token) => {

    return (dispatch, getState) => {
        dispatch(loadProfileStart())
        const getUrl = URL + 'myprofile/'
        return axios.get(getUrl, {
            headers: {
                ...HEADERS,
                'Authorization': 'Token ' + token // token is in another reducer,
            }
        })
            .then(res => {
                dispatch(loadProfileSuccess(res.data.profile))
                return res.data.profile

            })
            .catch(err => {

                dispatch(loadProfileFail(err))
                throw (err)
            })
    }
}

我做了一些研究,说我应该使用middleware。但是我仍然不了解getState,因为我的商店位于App.js

const store = createStore(rootReducer, compostEnhancer(
    applyMiddleware(thunk )
))

const app = (
    <Provider store={store}>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </Provider>)

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在我的项目中,如果用户登录,则在App构造函数中进行测试。为此,我将Redux状态控制为变量isLoggedIn。我为此使用mapStateToProps。

如果isLoggedIn我从API获取令牌,然后将他保存在localstorage中,那么我将显示主目录组件,否则就是!isLoggedIn我将显示loggin组件。 希望这种方式对您有所帮助。