Получение реквизита не определено при вызове Redux Axios API - PullRequest
0 голосов
/ 03 октября 2018

Для жизни я не могу понять эту проблему.Я пытаюсь отобразить информацию о пользователе, и я знаю, что API работает на 127.0.0.1/api/user/1.Тем не менее, когда я пытаюсь передать параметры, я получаю реквизиты не определены.Вот мой маршрутизатор, чтобы доказать, что я передаю идентификатор

import React from 'react'
import { Route } from 'react-router-dom'
import ArticleListView from '../containers/ArticleListView'
import ArticleDetailView from '../containers/ArticleDetailView'
import SignUp from '../containers/SignUp'
import UserDetailView from '../components/UserInformation';


const BaseRouter = () => (
    <div>
        <Route exact path='/' component={ArticleListView} /> 
        <Route exact path='/:cid' component={ArticleDetailView} />
        <Route exact path='/signup' component={SignUp} />
        <Route exact path='/user/:id' component={UserDetailView} />
    </div>
)

export default BaseRouter

Вот действие, которое становится неопределенным:

import axios from "axios";
import {  thunk  }  from 'react-redux'

export function getUser() {


  return dispatch => {

     dispatch(fetchUserBegin());
     const id = this.props.params.match.id
     return axios.get(`/api/user/${id}`)
      .then( res => { 
        dispatch(fetchUserSuccess(res.data)
      )})
      }
 }

export const FETCH_USER_BEGIN   = 'FETCH_USER_BEGIN';
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS';
export const FETCH_USER_FAILURE = 'FETCH_USER_FAILURE';

export const fetchUserBegin = () => ({
  type: FETCH_USER_BEGIN
});

export const fetchUserSuccess = user => ({
  type: FETCH_USER_SUCCESS,
  payload: { user }
});

export const fetchUserFailure = error => ({
  type: FETCH_USER_FAILURE,
  payload: { error }
});

Редуктор

import {  FETCH_USER_BEGIN, FETCH_USER_SUCCESS, FETCH_USER_FAILURE  } from '../actions/actionTypes'


const initialState = {
    user: {},
    loading: false,
    error: null
  };

  export default function userReducer(state = initialState, action) {
    switch(action.type) {
      case FETCH_USER_BEGIN:
        // Mark the state as "loading" so we can show a spinner or something
        // Also, reset any errors. We're starting fresh.
        return {
          ...state,
          loading: true,
          error: null
        };

      case FETCH_USER_SUCCESS:
        // All done: set loading "false".
        // Also, replace the items with the ones from the server
        return {
          ...state,
          loading: false,
          user: action.user
        };

      case FETCH_USER_FAILURE:
        // The request failed, but it did stop, so set loading to "false".
        // Save the error, and we can display it somewhere
        // Since it failed, we don't have items to display anymore, so set it empty.
        // This is up to you and your app though: maybe you want to keep the items
        // around! Do whatever seems right.
        return {
          ...state,
          loading: false,
          error: action.payload.error,
          user: {}
        };

      default:
        // ALWAYS have a default case in a reducer
        return state;
    }
  }

Магазин:

const reducer = combineReducers({
    user: userReducer,
    articles: articleReducer
})


const store  = createStore(reducer, composeEnhances(
    applyMiddleware(thunk)
))

Дисплей компонента

    import React from "react";
import { connect } from "react-redux";
import { getUser } from "../store/actions/userActions";

class UserDetailView extends React.Component {
  componentDidMount() {
    this.props.getUser()  //fixed
  }

  render() {
    const { user } = this.props;
    console.log(user)

    return (
      <ul>
        {user.map(user =>
          <li key={user.id}>{user.username}</li>
        )}
      </ul>
    );
  }
}

const mapStateToProps = state => ({
  user: state.user,
});
const mapDispatchToProps = dispatch => ({   //added
  getUser: dispatch(getUser())
})

export default connect(mapStateToProps,mapDispatchToProps)(UserDetailView);  //fixed

1 Ответ

0 голосов
/ 03 октября 2018

Получите пользовательские данные из объекта полезной нагрузки, потому что метод getUser отправляет данные в action.payload.user.

case FETCH_USER_SUCCESS:
        // All done: set loading "false".
        // Also, replace the items with the ones from the server
        return {
          ...state,
          loading: false,
          user: action.payload.user
        };
...