gpt4 book ai didi

javascript - 在react+redux应用程序的Home组件中,在componentdidmount上调用action getPosts()后,this.props.posts未定义

转载 作者:行者123 更新时间:2023-12-02 23:18:59 25 4
gpt4 key购买 nike

我正在尝试制作一个博客风格的应用程序。我正在运行 django 服务器并尝试制作一个 React-Redux 前端。我正在使用 redux-devtools,当我注释掉错误代码时,redux 似乎有状态中的数据。不知道出了什么问题。另外,我使用 redux-thunk 和 axios 与后端通信。我几乎是从 YouTube 教程中复制的。这是 reducer reducers/posts.js


import {GET_POSTS} from "../actions/types";

const initialState = {
posts: []
}

export default function(state = initialState, action) {
switch (action.type) {
case GET_POSTS:
return {
...state,
posts: action.payload
}
default:
return state;
}
}

这是操作 actions/posts.js


import axios from "axios";
import {GET_POSTS} from "./types";

export const getPosts = () => dispatch => {
axios.get('/get/posts/').then(res => {
dispatch({
type: GET_POSTS,
payload: res.data
})
}).catch(error => {console.log(error)})
}

这是reducers/index.js


import {combineReducers} from 'redux';
import posts from "./posts";
export default combineReducers({
posts
});

这是 store.js


import {createStore, applyMiddleware} from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initialState = {};

const middleware = [thunk];

const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;

这是组件/Home.js(此处错误)


import React from 'react';
import {connect} from 'react-redux';
import {getPosts} from '../actions/posts';
class Home extends React.Component {
componentDidMount() {
this.props.getPosts();
}
render() {
console.log(this.props.posts); //undefined
const posts = this.props.posts.map(post => (
<div className="post">
<h1>{post.title}</h1>
<p>{post.message}</p>
</div>
)
)
return (
{posts}
)
}
}
const mapStateToProps = state => ({
posts: state.posts // I have tried state.posts
// and state.posts.posts. I think
//state.posts might be undefined which is
//causing this.props.posts to be undefined in the component
});
export default connect(mapStateToProps, {getPosts})(Home);

解答:我发现 render 被调用了多次,第一次调用时,this.props.posts 未定义,所以我添加了一个 if 语句来判断 this.props.posts 是否未定义以及是否未定义,我渲染列表。

最佳答案

返回时在 Home 组件内执行以下操作:

return (
{this.posts.length > 0 && posts}
)

您的初始渲染正在尝试渲染尚未从服务器获取的元素数组。对 Web API 和后端服务器的所有 fetch 调用都是异步的,这意味着一旦 JS 引擎的堆栈帧空闲,它们就会立即执行。添加条件语句将允许您执行额外的检查,这将重新呈现页面,因为数据将被提取并存储到您的 reducer 中。此外,当不确定 Redux 存储的状态/形状时,您可以随时通过控制台记录它,如下所示:

const mapStateToProps = state => {
console.log(state);
return {
posts: state.posts
}
}

关于javascript - 在react+redux应用程序的Home组件中,在componentdidmount上调用action getPosts()后,this.props.posts未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57031618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com