【问题标题】:Props are undefined in Functional React Component功能性 React 组件中未定义道具
【发布时间】:2020-11-27 01:48:14
【问题描述】:

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

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

我不确定为什么 props 未定义并且没有任何操作。

【问题讨论】:

  • 如果你使用钩子,为什么不使用useSelector钩子?
  • 'useEffect(() => { let test = props.actions.getSomething(); },[props]);'试试这个,这样每当 props 改变时,useEffect 就会被再次调用

标签: reactjs redux react-redux


【解决方案1】:

改用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 钩子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2020-09-15
    • 2022-11-12
    • 2020-04-30
    • 1970-01-01
    • 2021-03-25
    • 2021-02-27
    • 2021-10-22
    相关资源
    最近更新 更多