如何使用useSelector及其等效的mapdispatch

问题描述 投票:0回答:1

我正在研究如何将连接代码转换为 redux 中的 useSelector。 useSelector api 中的 mapDispatchProps 相当于什么? 如何将以下两段代码转换为 useSelector api?

const mapStateToProps = (state) => ({ currentUser: state.user, });

const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUser, fetchUserPosts }, dispatch);

export default connect(mapStateToProps, mapDispatchProps)(main);

import React from 'react'
import { View, Text, Image, FlatList } from 'react-native'
import { auth } from '../../firebaseConfig'

import { fetchUserPosts } from '../../redux/actions/index.js'

import { connect } from 'react-redux'

function Profile(props) {
  const { currentUser, posts } = props;
  console.log({ currentUser, posts });
  return (
    <View>
      <Text>Profile</Text>
    </View>
  )
}

const mapStateToProps = (store) => ({
  currentUser: store.userState.currentUser,
  posts: store.userState.posts,
})

export default connect(mapStateToProps, null)(Profile);

javascript react-native redux expo dispatch
1个回答
0
投票
import React from "react";
import { View, Text, Image, FlatList } from "react-native";
import { auth } from "../../firebaseConfig";

import { fetchUserPosts } from "../../redux/actions/index.js";

import { useSelector, useDispatch } from "react-redux";

export default function Profile(props) {
  const currentUser = useSelector((state) => state.userState.currentUser);
  const posts = useSelector((state) => state.userState.posts);
  // if you need dispatch in a component
  const dispatch = useDispatch();

  return (
    <View>
      <Text>Profile</Text>
    </View>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.