javascript - 为什么我的状态变量未为 props.location.state 定义?
问题描述
我正在使用 Link 将数据从一个页面传输到另一个页面。我也可以在新页面上获取数据,我正在使用控制台检查这些数据。问题是,我无法使用 useState 使用此数据设置初始状态变量。下面是我的代码。
export default function myFunc(props) {
const { myData, setMyData } = useState(props.location.state);
// const { myData, setMyData } = useState({...props.location.state}); // This doesn't work either
console.log('props here', props.location.state); // see the required object
console.log('myData here', myData); // get undefined instead of the required object
为什么我的 myData 未定义?
解决方案
您应该在 useState 声明中使用方括号并使用useEffect
钩子显示myData
初始值。就像是:
const [myData, setMyData] = useState(props.location.state);
console.log('props here', props.location.state);
useEffect(() => {
console.log(myData);
},[myData])
推荐阅读
- python - PyHook 只在某些时候有效,而不是始终如一
- linux - 使用 Linux 将预告片添加到 csv
- python - 使用 Spyder IDE 和 virtualenv。更改解释器但似乎没有更新
- exception - Yii2 - 捕获需要错误
- sql - Pyspark 自加入创建网络数据
- windows - 添加名称中带有空格的 Active Directory 组会导致 PowerShell 脚本出错
- javascript - Chrome 的 tabcapture api 没有在标签上录制所有音频
- python - python TypeError 不可散列的类型列表
- c++ - 在地图上启动对象的正确方法
- java - Spring Cloud(Netflix OSS)与 WSO2