【问题标题】:Can I use useEffect hook and function component when I need to get the pathname props from Link component?当我需要从 Link 组件中获取路径名道具时,我可以使用 useEffect 钩子和函数组件吗?
【发布时间】:2021-08-13 21:17:42
【问题描述】:

这些天我开始学习 React.js。

我想知道我是否可以使用useEffect钩子和函数组件而不是componentDidMount()和类组件,例如,当用户直接访问“http://localhost:3000/movie-detail”而不点击在“电影”链接上。

我尝试了一些方法,我认为,在这种情况下,我必须使用componentDidMount() 和类组件,因为必须单击“电影”链接才能将props 传递给“详细信息”组件。

如果你知道如何处理这个问题,可以告诉我吗?



这是我的“电影”组件,其中有一个路径名道具。

function Movie({id, year, title, summary, poster, genres}){
    return (
        <Link
          to={{
            pathname:"/movie-detail",
            state: {
                year,
                title,
                summary,
                poster,
                genres
            }
          }}
         >
           <div className="movie">
                ...
           </div>
       </Link>
    )
}



这是我的“应用程序”组件,其中将路径名道具传递给“详细信息”组件。

function App() {
  return (
    <BrowserRouter>
      <Navigation />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/movie-detail" component={Detail} />
      </Switch>
    </BrowserRouter>
  )
}



这是我的“详细信息”组件,其中获取表单 Route 组件的道具。

function Detail({location, history}) {

  useEffect(() => {
     if(location === undefined) {
       history.push("/");
     }
   }, [ location, history])

  const { title } = location.state;

  return (
   <h1>Title: {title}</h1>
  )
}



我得到如下错误代码。

TypeError: Cannot destructure property 'title' of 'location.state' as it is undefined.

【问题讨论】:

  • 我想我也许可以用“useHistrory”或“useLocation”来处理它。

标签: javascript reactjs use-effect


【解决方案1】:

我认为这里的问题不在于您可以使用 useEffect 的方式,而是要回答您的问题,是的,您绝对可以在功能组件中使用 useEffect 来代替 componentDidMount。

如果我们查看错误,您的代码会抛出它,因为它无法接收位置变量中的值,因此无法重构该值。

我们在 react 中使用的链接实际上类似于 HTML 中的锚标签。我们也可以在 react 中使用相同的,但避免使用它们的原因是因为它们会重新渲染您的完整页面,并做出反应库仅重新呈现页面中已更改的那些部分,其余部分保持不变。因此我们不喜欢在反应中使用锚标签。您可以从以下链接进一步了解相同内容:- https://www.pluralsight.com/guides/understanding-links-in-reactjs 在 to 对象中传递的所有数据都在 props 中接收:- 您可以点击以下链接:-https://stackoverflow.com/questions/30115324/pass-props-in-link-react-router , https://medium.com/@bopaiahmd.mca/how-to-pass-props-using-link-and-navlink-in-react-router-v4-75dc1d9507b4

现在,我相信您可以通过以下方式重构您的代码:-

function Detail(props) {

  useEffect(() => {
     if(props.location === undefined) {
       history.push("/");
     }
   }, [ props.location, props.history])

  const { title } = props.location.state;

  return (
   <h1>Title: {title}</h1>
  )
}

【讨论】:

  • 感谢您回答我。我试过了,但还是不行。我会去找你给我的链接作为参考。 :-)
【解决方案2】:

修改路由路径到 /movie-detail/:id , 刷新页面时,可以从服务器加载电影数据

function Movie({id, year, title, summary, poster, genres}){
    return (
        <Link
          to={{
            pathname:"/movie-detail/" + id,
            state: {
                year,
                title,
                summary,
                poster,
                genres
            }
          }}
         >
           <div className="movie">
                ...
           </div>
       </Link>
    )
}

function App() {
  return (
    <BrowserRouter>
      <Navigation />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/movie-detail/:id" component={Detail} />
      </Switch>
    </BrowserRouter>
  )
}

function Detail({location}) {

  
  const [state, setState] = useState(location && location.state);
  const id = location && location.params.id;
  useEffect(()=> {
    if (id){
      fetch('/api/movie/' + id)
         .then((x)=> x.json())
         .then((x)=> setState(x));
    }
  }, [!state, id])
  if (!location || !id){return <Redirect to="/" />}
  if (!state) return <div>Loading.....</div>
  return (
   <h1>Title: {state.title}</h1>
  )
}

【讨论】:

  • 谢谢。我尝试过这个 。但它仍然无法正常工作。即使我将 id 道具添加到 Movie 组件中的“状态”对象,我也收到类似“TypeError:无法读取未定义的属性 'id'”的错误。但我想我可以通过 Redirect 、 useLocation 或 useHistory 来解决。
猜你喜欢
  • 1970-01-01
  • 2021-01-16
  • 2017-10-10
  • 2023-01-12
  • 2018-10-29
  • 2022-01-07
  • 2020-09-14
  • 2021-03-16
  • 2020-01-01
相关资源
最近更新 更多