Reactjs 类和类之间的redux操作调度有何不同;功能组件?
我想知道功能组件中的redux实现与类组件有什么不同Reactjs 类和类之间的redux操作调度有何不同;功能组件?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我想知道功能组件中的redux实现与类组件有什么不同 import React, { Component } from "react"; class Posts extends Component { componentDidMount() { this.props.fetchPosts(); } render() { let postItems = this.props.posts.map((post) => ( <d
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>;
};
因为我得到了一个有效的例子,而不是有效的例子
工作示例是类组件。当我使用类组件并使用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>;
};
未将项分配给任何对象,因为传递给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 ) */);
您也可以有一个没有主体的arrow函数,那么箭头后面的任何内容都是返回值。例如:constadd=(a,b)=>a+b
如果有一个返回对象的无体箭头函数,它会让人感到困惑,因为对象和函数体具有相同的语法{}
,所以要返回对象,可以执行({})
,下面是一个示例:const add=(a,b)=>({sumAB:a+b})
。对于jsx,()
是可选的,因此常量hello=()=>hello代码>和常量hello=()=>(hello)代码>都是有效的。当返回多行jsx时,诸如prettier之类的格式化程序通常会使用()
对其进行格式化,如下所示:
const hello = () => (
<div>
<div>hello</div>
</div>
);
const hello=()=>(
你好
);