在函数式React组件中未定义道具

时间:2020-08-06 18:27:46

标签: reactjs redux react-redux

我正在使用Redux模式,并且具有一个需要调用redux动作的功能组件,但我的道具始终未定义

const GetCustomers= (props) => {

  useEffect(() => {
    //Props is always undefined?
    let test = props.actions.getSomething();   
  });

  return (
    <>Hello</>
);};
GetCustomers.propTypes = {
  actions: PropTypes.object.isRequired
};

export default GetCustomers;

然后我为mapDisplayToProps有另一个js文件


const mapStateToProps = (state) => state.reducer;
const mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(GetCustomers);

我不确定为什么道具没有定义并且没有任何动作。

1 个答案:

答案 0 :(得分:0)

代替mapStateToPropsmapDispatchToProps

要选择state的一部分,请执行

import {useSelector} from 'react-redux'

const GetCustomers= (props) => {
yourStateName = useSelector(state => state.yourState)
//OR if you have multiple reducers combined use this
yourStateName = useSelector(state => state.reducerYourStateBelongsTo.yourState)
}

对于Dispatching动作执行此操作

import {useSelector} from 'react-redux'
import {yourAction} from '../path'
const GetCustomers= (props) => {
const dispatch = useDispatch()
dispatch(yourAction(args if any pass it here))
}

如果您正在使用功能组件,则认为最好使用useSelectoruseDispatch钩子