React Redux中this.props.streams为undefined,后端返回正常求助
前端项目问题整理
我发现无论怎么操作,组件中this.props.streams的值始终为undefined。我已确认后端API被查询时可正常返回数据,返回示例如下:
[ { "welcome": "Livestream service", "livestreamURL": "https://", "replayURL": "https://", "completedURL": "https://", "_id": "6027e477fe33c55e8c5eef9c", "title": "Service for derping", "owner": "Derpface", "serviceDate": "2021-02-25T12:00:00.000Z", "dateAdded": "2021-02-13T14:38:47.673Z", "__v": 0 }, { "welcome": "Livestream service", "livestreamURL": "https://", "replayURL": "https://", "completedURL": "https://", "_id": "6027e47afe33c55e8c5eef9d", "title": "Service for derping", "owner": "Derpface", "serviceDate": "2021-02-25T12:00:00.000Z", "dateAdded": "2021-02-13T14:38:50.749Z", "__v": 0 } ]
无论我怎么尝试,都无法将接口返回的结果填充到props中,以下是涉及的相关文件代码:
相关文件代码
问题文件:client/src/components/StreamList.js
import { Container, ListGroup, ListGroupItem, Button } from "reactstrap"; import { CSSTransition, TransitionGroup } from "react-transition-group"; import { connect } from "react-redux"; import { getStreams, deleteStream, addStream } from '../actions/streamActions'; import PropTypes from "prop-types"; class StreamList extends Component { static propTypes = { getStreams: PropTypes.func.isRequired, stream: PropTypes.object.isRequired, isAuthenticated: PropTypes.bool, }; componentDidMount() { this.props.getStreams(); } onDeleteClick = (_id) => { this.props.deleteStream(_id); }; render() { const { streams } = this.props.streams; return ( <Container> {this.props.isAuthenticated ? ( <> <h2>You're logged in.</h2> <ListGroup> <TransitionGroup className="stream-list"> {streams.map(({ _id, title }) => ( <CSSTransition key={_id} timeout={500} classNames="fade"> <ListGroupItem> {this.props.isAuthenticated ? ( <Button className="remove-btn" color="danger" size="sm" onClick={this.onDeleteClick.bind(this, _id)} > ×{" "} </Button> ) : null} {title} </ListGroupItem> </CSSTransition> ))} </TransitionGroup> </ListGroup> </> ) : <h2>You must be logged in to see conent</h2>} </Container> ); } } const mapStateToProps = (state) => ({ stream: state.stream, isAuthenticated: state.auth.isAuthenticated, }); export default connect(mapStateToProps, { getStreams, deleteStream })(StreamList);
client/src/streamActions.js
import axios from "axios"; import { GET_STREAMS, ADD_STREAM, DELETE_STREAM, STREAMS_LOADING } from "./types"; import { tokenConfig } from "./authActions"; import { returnErrors } from "./errorActions"; export const getStreams = () => (dispatch) => { dispatch(setStreamsLoading()); axios .get("/api/streams") .then((res) => dispatch({ type: GET_STREAMS, payload: res.data, }) ) .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)) ); }; export const addStream = (stream) => (dispatch, getState) => { axios .post("/api/streams", stream, tokenConfig(getState)) .then((res) => dispatch({ type: ADD_STREAM, payload: res.data, }) ) .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)) ); }; export const deleteStream = (id) => (dispatch, getState) => { axios .delete(`/api/streams/${id}`, tokenConfig(getState)) .then((res) => dispatch({ type: DELETE_STREAM, payload: id, }) ) .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)) ); }; export const setStreamsLoading = () => { return { type: STREAMS_LOADING, }; };
client/src/reducers/streamReducer.js(原路径拼写错误:stc应为src)
import { GET_STREAMS, ADD_STREAM, DELETE_STREAM, STREAMS_LOADING } from '../actions/types'; const initialState = { streams: [], loading: false } export default function(state = initialState, action) { switch(action.type) { case GET_STREAMS: return { ...state, streams: action.payload, loading: false }; case DELETE_STREAM: return { ...state, streams: state.streams.filter(stream => stream._id !== action.payload) }; case ADD_STREAM: return { ...state, streams: [action.payload, ...state.streams] }; case STREAMS_LOADING: return { ...state, loading: true }; default: return state; } }
client/src/App.js
import React, { Component } from 'react'; import { BrowserRouter as Router, Link, Route } from 'react-router-dom'; import AppNavbar from './components/AppNavbar'; // import ShoppingList from './components/ShoppingList'; import { Provider } from 'react-redux'; import store from './store'; // import ItemModal from './components/ItemModal'; import { Container } from 'reactstrap'; import { loadUser } from './actions/authActions'; import StreamList from './components/StreamList'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import PassResetForm from './components/auth/PassResetForm'; import UserProfile from './components/auth/UserProfile'; class App extends Component { componentDidMount() { store.dispatch(loadUser()); } render() { return ( <Router> <Provider store={store}> <div className="App"> <AppNavbar /> <Container> <Route exact={true} path="/api/users/resetpassword/:resetLink" component={PassResetForm} /> <Route exact={true} path="/api/auth/:user" component={UserProfile} /> <StreamList /> </Container> </div> </Provider> </Router> ); } } export default App;
后端路由 /routes/api/streams.js
const express = require("express"); const router = express.Router(); const auth = require("../../middleware/auth"); // Item model const Stream = require("../../models/Stream"); // @route GET api/streams // @desc GET all Streams // @access Private router.get("/", (req, res) => { console.log('router.get /streams') Stream.find() .sort({ date: -1 }) .then((streams) => res.json(streams)); // console.log(streams) }); // @route POST api/streams // @desc Create an stream // @access Private router.post("/", (req, res) => { const newStream = new Stream({ title: req.body.title, owner: req.body.owner, serviceDate: new Date(req.body.serviceDate), }); newStream.save().then((stream) => res.json(stream)); }); module.exports = router;
十分感谢各位提供的帮助,抱歉贴了大量代码。
问题定位与修复
核心错误
你在StreamList.js的render函数中取props的字段名有误。mapStateToProps将state.stream(整个stream reducer的状态对象,包含streams列表、loading字段)赋值给组件的stream(单数)prop,而非streams(复数)prop。
原代码取值逻辑:
const { streams } = this.props.streams;
this.props上不存在streams字段,自然返回undefined,解构操作也会触发报错。
正确写法:
const { streams } = this.props.stream;
额外排查项
- 确认
combineReducers配置中,stream reducer挂载的键名为stream,需和mapStateToProps中读取的state.stream对应。示例配置:
// store.js 示例 import { combineReducers } from 'redux'; import authReducer from './reducers/authReducer'; import streamReducer from './reducers/streamReducer'; export default combineReducers({ auth: authReducer, stream: streamReducer // 键名必须匹配 });
如果挂载键名错误(如写成streamList),会直接导致state.stream为undefined。
- 你导入了
addStreamaction但未在connect的第二参数中传入,后续如果要调用该方法需补全:
export default connect(mapStateToProps, { getStreams, deleteStream, addStream })(StreamList);
- 你贴的reducers路径写为
/client/stc/reducers,是src的拼写错误,注意修正导入路径避免模块加载失败。
内容的提问来源于stack exchange,提问作者Newsworthy
相关产品推荐
相关产品推荐

