首页 > 解决方案 > 类和函数组件之间的 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);

标签: reactjsreduxreact-redux

解决方案


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>
);

推荐阅读