reactjs - 类和函数组件之间的 redux 动作调度有何不同?
问题描述
我想知道功能组件中的 redux 实现与类组件有何不同。
因为我有一个工作示例而不是工作示例。
工作示例是类组件。当我使用类组件并使用它时,props.fetchSomething
它总是有效的。
这是类组件。
import React, { Component } from "react";
class Posts extends Component {
componentDidMount() {
this.props.fetchPosts();
}
render() {
let postItems = this.props.posts.map((post) => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
));
return <div>{postItems}</div>;
}
}
现在我将向您展示功能组件的不工作版本。
import React, { useEffect } from "react";
const Posts = ({ fetchPosts, posts }) => {
useEffect(() => {
fetchPosts();
}, []);
let items = posts.map((post) => {
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>;
});
return <div>{items}</div>;
};
如您所见,FROM MY UNDERSTANDING
这两个工作相同,因为我在安装状态下获取数据并映射存储数据。
这是我剩下的代码。这是redux操作。我将以下这些代码用于类和函数组件。问题是,只有类组件显示数据列表。函数组件总是返回一个空数组。
这是为什么
Posts.propTypes = {
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.array.isRequired,
newPost: PropTypes.object,
};
const mapStateToProps = (state) => ({
// coming from root reducer
posts: state.posts.itemsArray,
newPost: state.posts.item,
});
export default connect(mapStateToProps, { fetchPosts })(Posts);
解决方案
Items 没有分配给任何东西,因为传递给 map 的回调函数不返回任何东西:
useEffect(() => {
fetchPosts();
//you should really try using create-react app, then
// you'd see the missing dependency when compiling
// When you also set up vs code you'd see it when you
// open the file in the editor
}, [fetchPosts]);
//in VS code you would have a linter warning:
// Expected to return a value in arrow function.
// also defined items as const
const items = posts.map((post) => (//replaced { with (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>//removed ;
)/**replaced } with ) */);
如果你{...}
在箭头函数的箭头之后使用,那么...
就是函数的主体,你必须从这个主体返回一些东西:
let items = posts.map((post) => {
return (//have to return jsx
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
); //removed ;
});
你也可以有一个没有主体的箭头函数,那么箭头后面的就是返回值。例如:const add = (a,b)=>a+b
。
如果你有一个返回对象的无体箭头函数,它会让人感到困惑,因为对象和函数体具有相同的语法{}
,所以要返回一个对象,你可以这样做({})
,这里有一个例子const add = (a,b)=>({sumAB:a+b})
:使用 jsx(<jsx />)
是可选的,所以const hello = () => <div>hello</div>;
都是const hello = () => (<div>hello</div>);
有效的。当返回多行 jsx 时,prettier 之类的格式化程序通常会(<jsx />)
像这样格式化它:
const hello = () => (
<div>
<div>hello</div>
</div>
);
推荐阅读
- mysql - MYSQL:如何将唯一随机数更新到现有行
- javascript - 在useEffect中从实时firebase中检索数据返回未定义
- android - ArFragment SceneView 在使用 ViewBinding 时返回 Null
- r - 从 R 中 pheatmap 中未选择的行名中删除 NA
- javascript - mongoose insertMany() 方法的数组无法正常工作!任何人都知道为什么?
- c# - PackageReference 到同一解决方案/git 存储库中的项目
- php - 如何获得相同的日期、开始时间和结束时间表单数据库,其中日期我有多次
- java - 具有并行元素和顺序元素的 Java 流
- python - Python 乌龟:tkinter 的问题
- python - 如何将字符串对象与张量(tf.string)如 pathlib.Path 与 TensorFlow 连接?