React函数组件是否可以同时传入props和额外的解构赋值参数?
你现在的写法完全无法生效,React 函数组件不支持自定义第二个入参。
React 函数组件的入参规则是固定的:
- 普通组件仅接收第一个参数,即所有父组件/Redux 映射传递的属性集合
props - 只有使用
React.forwardRef包裹的组件,才会有第二个参数,且固定为ref对象,不能自定义解构其他值
正确实现方案
方案1:所有值从 props 中获取(适配你当前用 connect 映射 Redux 状态到 props 的写法)
把你需要的cityData直接从 props 里解构即可,代码示例:
import { useEffect } from 'react' import Typography from '@mui/material/Typography' // 参数位直接解构需要的属性,剩余属性用rest接收 function MyFunction({ fetchCity, cityData, ...otherProps }) { console.log(otherProps) // 其他未显式解构的自定义props都在这里 useEffect(() => { fetchCity() }, [fetchCity]) // 必须添加依赖,避免闭包问题 return cityData.loading ? ( <Typography>Loading</Typography> ) : cityData.error ? ( <Typography>{cityData.message}</Typography> ) : ( <div></div> ) }
方案2:使用 Redux 官方推荐的 Hooks 写法(更简洁,无需connect映射)
如果你用的是react-redux@7.1+版本,直接用useSelector和useDispatch在组件内部获取状态和触发action,不需要把Redux状态挂载到props上:
import { useEffect } from 'react' import Typography from '@mui/material/Typography' import { useSelector, useDispatch } from 'react-redux' // 引入你的获取城市列表的action创建函数 import { fetchCity } from '@/store/actions/city' function MyFunction(props) { const dispatch = useDispatch() // 按你的Redux store实际结构调整取值路径 const cityData = useSelector(state => state.cityModule.cityData) useEffect(() => { dispatch(fetchCity()) }, [dispatch]) return cityData.loading ? ( <Typography>Loading</Typography> ) : cityData.error ? ( <Typography>{cityData.message}</Typography> ) : ( <div></div> ) }
注意事项
- 不要给
useEffect留空依赖数组,所有在回调内部用到的外部变量都要加入依赖列表,dispatch本身是稳定引用,不会触发重复执行 - 如果你确实需要接收父组件额外传递的自定义属性,所有属性都会统一挂载到第一个
props参数上,直接从props取值即可
内容的提问来源于stack exchange,提问作者Alazar-dev
相关产品推荐
相关产品推荐

