反应从Api获取Redux initialState

时间:2019-06-05 17:34:31

标签: reactjs react-redux redux-thunk

我正在使用JWT auth,当用户登录时,我将令牌存储在localstorage中。如何使用该令牌获取api,以便在页面出现时可以获取用户详细信息 第一次加载。

我已经在使用React Thunk进行异步请求,但是我不知道如何通过异步请求设置initialState。但是可以在reducer中设置本地存储吗?

1 个答案:

答案 0 :(得分:2)

您可能想在操作中执行以下操作:

import axios from 'axios';

export const LOADING = "LOADING";
export const SUCCESS = "SUCCESS";
export const FAILURE = "FAILURE";
export const UPDATE = "UPDATE";
export const SUCCESSFUL_UPDATE = "SUCCESSFUL_UPDATE";

export const getSmurfs = () => dispatch => {
    dispatch({ type: LOADING })
  axios.get('http://localhost:3333/smurfs')
    .then(res => dispatch({ type: SUCCESS, payload: res.data}))
    .catch(err => dispatch({ type: FAILURE, payload: err}))
}

因此,您将从加载状态开始,该状态将根据响应更改为成功或失败。然后在您的减速器中,您需要执行以下操作:

import { LOADING, SUCCESS, FAILURE, UPDATE, SUCCESSFUL_UPDATE } from '../actions/index';

const initialState = {
  smurfs: [],
  loading: false,
  error: "",
  updateID: "",
  clicked: false,
  update: []
}

export default function reducer(state= initialState, action) {
  switch(action.type) {
    case LOADING:
      return {
        ...state,
        smurfs: [],
        loading: true,
        err: ''
      }

    case SUCCESS:
      return {
        ...state,
        smurfs: action.payload,
        loading: false,
        err: ''
      }

基本上,一旦成功,它将关闭加载并显示您返回的数据

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { getSmurfs, deleteSmurf, update } from '../actions/index';

import Smurfs from './smurfs';
import Form from './form';
import UpdateForm from './updateForm';

class SmurfsViewer extends Component {

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

    render() {
        console.log(this.props.smurfs)
        // if loading returns true then display loading smurfs..
        if(this.props.loading) {
            return (<h1>LOADING SMURFS....</h1>)
        }

        //if clicked resolves true then display the form to allow updating of the smurf that had its edit button clicked
        let form;
        if(this.props.clicked) {
            form = <UpdateForm />
        } else {
            form = <Form />
        }

        return(
            <div>
                <Smurfs smurfs={this.props.smurfs} deleteSmurf={this.props.deleteSmurf} update={this.props.update}/>
                {form}
            </div>
        )
    }
}

const mstp = state => {
    console.log("FROM VIEWER:", state)
    return {
        smurfs: state.smurfs,
        loading: state.loading,
        clicked: state.clicked
    }
}

export default connect(mstp, { getSmurfs, deleteSmurf, update })(SmurfsViewer);

因此,您需要通过mapStateToProps(mstp)从Redux发送状态并连接方法。然后,您可以在组件中使用它们,它将根据需要更新您的redux状态。然后只需将它们称为this.props.getSmurfs或类似的内容