弄清楚如何使用这种方式将 redux 与钩子一起使用,但不确定它是正确的方法
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getPins } from "../../../actions/pins";
function MainStory() {
const pins = useSelector(state => state.pins.pins);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPins(pins));
}, []);
console.log(pins);
return(<div> test </div>
尽管缺少依赖项,但上述方式是否是正确的方法?
React Hook useEffect缺少依赖项:"dispatch"和"pins"。包含它们或删除依赖项数组
使用组件(我以前拥有的方式(
import { getPins } from "../../actions/pins";
import { connect } from "react-redux";
import PropTypes from "prop-types";
export class Pins extends Component {
static propTypes = {
pins: PropTypes.array.isRequired,
getPins: PropTypes.func.isRequired
};
componentDidMount() {
this.props.getPins();
}
render() {
console.log(this.props.pins);
return <div>test</div>;
}
}
const mapStateToProps = state => ({
pins: state.pins.pins
});
export default connect(mapStateToProps, { getPins })(Pins);
计划是列出每个引脚
您可以将dispatch
添加到依赖项列表中,因为它不会更改。如果要将pins
添加到useEffect
块的依赖项列表,则如果对操作的响应更改状态(调用返回数组的服务器(,则可能会导致无限循环。
但是,根据类组件示例,getPins()
动作创建者不需要pins
的值,因此您只需将dispatch
添加到依赖项列表中即可:
function MainStory() {
const pins = useSelector(state => state.pins.pins);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPins());
}, [dispatch]);
console.log(pins);
return(<div> test </div>