Rhi*_*omb 16 javascript undefined reactjs redux react-hooks
useState()
给我未定义的新状态变量(通知):
const Notifications = (props) => {
const [notifications, setNotifications] = useState(props.notifications);//notifications = undefined, props = {notifications: Array(0)}
useEffect(() => {
if (props.notifications) {
setNotifications(props.notifications);
}
}, [props.notifications]);
// do stuff....
Run Code Online (Sandbox Code Playgroud)
我期待通知[]
,然后随后setNotifications()
在props.notifications
更改时更新它。props.notification
来自 redux 商店。我不知道这是否会改变任何东西,但我确实设置了一个初始状态。
const initialState = Immutable.fromJS({
notifications: [],
});
Run Code Online (Sandbox Code Playgroud)
不知道为什么我变得未定义...
编辑:摆脱了错字和测试代码
要正确设置初始状态,您应该将其useState
作为参数传递给,因此:
const [notifications, setNotifications] = useState([]);
Run Code Online (Sandbox Code Playgroud)
此外,无论您是否props.notifications
在某处设置外部,但如果您依赖它在组件中具有某种默认值,那么您应该将其设置在那里,例如:
const Notifications = ({ notifications = [] }) => {
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的是,在依赖项列表中使用数组useEffect
有一些不需要的副作用,例如,如果notifications
结构将保持不变(相同的项目,相同的长度),但将是一个新数组,useEffect
将错过缓存,因为它只做一个肤浅的比较。考虑使用某种散列函数而不是数组本身(例如JSON.stringify
)