首页 > 解决方案 > 为什么我的状态变量未为 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 未定义?

标签: javascriptreactjsreact-hooks

解决方案


您应该在 useState 声明中使用方括号并使用useEffect钩子显示myData初始值。就像是:

  const [myData, setMyData] = useState(props.location.state);
  console.log('props here', props.location.state);

  useEffect(() => {
    console.log(myData);
  },[myData])

推荐阅读