javascript 新的 React Hook useState 返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55566085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New To React Hook useState Is Returning Undefined
提问by RhinoBomb
useState()is giving me undefined to the new state variable (notifications):
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....
I am expecting notifications to be []and then subsequently update it with setNotifications()when props.notificationschanges. props.notificationis coming from a redux store. I don't know if this changes anything but i did set an initial State.
我期待通知[],然后随后setNotifications()在props.notifications更改时更新它。props.notification来自 redux 商店。我不知道这是否会改变任何东西,但我确实设置了一个初始状态。
const initialState = Immutable.fromJS({
notifications: [],
});
Don't know why i am getting undefined...
不知道为什么我变得未定义...
Edit: Got rid of typo and testing code
编辑:摆脱了错字和测试代码
回答by jayarjo
To set initial state properly you should pass it to the useStateas an argument, so:
要正确设置初始状态,您应该将其useState作为参数传递给,因此:
const [notifications, setNotifications] = useState([]);
Also no matter if you set props.notificationsoutside somewhere or not, but if you rely on it having some kind of default value in the component, then you should set it right there, e.g.:
此外,无论您是否props.notifications在某处设置外部,但如果您依赖它在组件中具有某种默认值,那么您应该将其设置在那里,例如:
const Notifications = ({ notifications = [] }) => {
And the last but not the least, using array in dependency list of useEffecthas some unwanted side-effects, for example if notificationsstructuruly will stay the same (same items, same length), but will be a new array, useEffectwill miss a cache, since it only does a shallow comparison. Consider using a hashing function of some kind instead of the array itself (e.g. JSON.stringify)
最后但并非最不重要的是,在依赖项列表中使用数组useEffect有一些不需要的副作用,例如,如果notifications结构将保持不变(相同的项目,相同的长度),但将是一个新数组,useEffect将错过缓存,因为它只做一个肤浅的比较。考虑使用某种散列函数而不是数组本身(例如JSON.stringify)

