fetchById无法在反应中呈现状态,但console.log正确呈现状态

时间:2020-06-20 15:49:32

标签: javascript reactjs react-redux react-hooks react-router-dom

我有一个简单的react应用程序,其中我使用了react-redux,axios,react-router和功能组件。组件LMSCourseDetails.jsx如下:

import React, { useState, useEffect } from "react";
import {useDispatch,useSelector, useStore} from 'react-redux';
import { Link,useParams,useHistory } from 'react-router-dom';
import * as actions from "../_actions/courseActions";
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles({
  title: {
    fontSize: 14,
    display: 'flex',
  },
  pos: {
    marginBottom: 12,
  },
  card: {
    padding:10,
    marginTop:10,
    display: 'flex',
    flex:1,
  },
  cardAction: {
    display: 'block',
    textAlign: 'initial'
  },
  cardMedia: {
    width: 160,
  },
});

export default function LMSCourseDetails(props) {  
  const classes = useStyles();
  
 
     let {courseId}=useParams();
    
  const dispatch = useDispatch();
 
  useEffect(() => {
    dispatch(actions.fetchById(courseId));

   }, [])

  
  const course = useSelector(state=>state.course.list)
      
     
        console.log("course type:",typeof(course)); // type is object
  return (
  <div>
<h2> this is course {course.subject}</h2> // subject does not show here why????
</div>

    
  );
}

这是courseReducer.js

import { ACTION_TYPES } from '../_constants';

const initialState = {
    list: []
}


 export const course=(state = initialState, action)=>{

    switch (action.type) {
        case ACTION_TYPES.FETCH_ALL:
            return {
                ...state,
                list: [...action.payload]
            }
        case ACTION_TYPES.FETCH_BY_ID:
            return {
                ...state,
                list: [action.payload]  // i think here is error
            }
          
        default:
            return state
    }
}

courseApi.js从后端获取数据是 如下:

import axios from "axios";

const baseUrl = "http://localhost:4000/api/"



export default {

    course(url = baseUrl + 'courses/') {
        return {
            fetchAll: () => axios.get(url),
            fetchById: id => axios.get(url + id),
            create: newRecord => axios.post(url, newRecord),
            update: (id, updateRecord) => axios.put(url + id, updateRecord),
            delete: id => axios.delete(url + id)
        }
    }
}

console.log显示(学生的)旧状态,然后显示正确的课程状态,但未在return语句中显示{course.subject}。

courseActions.js如下:

import courseApi from "../_services/courseApi";
import { ACTION_TYPES } from '../_constants';


const formateData = data => ({
    ...data,
   // age: parseInt(data.age ? data.age : 0)
})

export const fetchAll = () => dispatch => {
      courseApi.course().fetchAll()
        .then(response => {
            
            dispatch({
                type: ACTION_TYPES.FETCH_ALL,
                payload: response.data
            })
        })
        .catch(err => console.log(err))
}
export const fetchById = (id) => dispatch => {
    courseApi.course().fetchById(id)
      .then(response => {
          
          dispatch({
              type: ACTION_TYPES.FETCH_BY_ID,
              payload: response.data
          })
      })
      .catch(err => console.log(err))
}


console.log screenshot here

1 个答案:

答案 0 :(得分:0)

它开始致力于将{course.subject}更改为{course [0] .subject}