无法重定向到未找到的页面(反应钩)

时间:2019-08-24 15:22:48

标签: reactjs react-hooks

我一直在尝试创建一个从我的详细信息组件到我的NotFound组件的重定向,但是我一直收到下面的TypeError。我认为我的if陈述在错误的地方吗?

Cannot read property 'title' of undefined
   8 | 
   9 | useEffect(() => {
  10 |   let tvShow = getGallery().find(gallery => gallery.id === tvShowId);
> 11 |   setDetailsText(tvShow.title);
     | ^  12 | }, [tvShowId]);
  13 | 
  14 | if(tvShowId === undefined) {

试图将我的if语句放在useEffect钩之前以及其中。

export default function Details(props) {
const [detailsText, setDetailsText] = useState();
const tvShowId = props.match.params.tvShowUrl;

  useEffect(() => {
    let tvShow = getGallery().find(gallery => gallery.id === tvShowId);
    setDetailsText(tvShow.title);
  }, [tvShowId]);

  if(tvShowId === undefined) {
    return <Redirect to = '/NotFound' />
  } else {
    return (
      <div>
        <h1>{detailsText}</h1>
        <Link to="/">Return to Home Page</Link>
      </div>
    )
  }
}

如果输入了错误的URL,我希望进行重定向。

2 个答案:

答案 0 :(得分:0)

我认为您快到了。您只需要避免该错误即可。

useEffect(() => {
    let tvShow = getGallery().find(gallery => gallery.id === tvShowId);

    if (tvShow) {
        setDetailsText(tvShow.title);
    }
}, [tvShowId]);

在这种情况下,useEffect的问题是:

  1. 该组件拥有额外的状态。
  2. props次更改它呈现两次,而不是一次。
  3. tvShow延迟到下一次渲染。

尝试以下方法:

export default function Details(props) {
    const tvShowId = props.match.params.tvShowUrl;

    const tvShow = useMemo(
        () => getGallery().find(gallery => gallery.id === tvShowId),
        [tvShowId]
    );

    if (tvShowId === undefined) {
        return <Redirect to="/NotFound" />
    } else {
        return (
            <div>
                <h1>{tvShow}</h1>
                <Link to="/">Return to Home Page</Link>
            </div>
        );
    }
}

答案 1 :(得分:0)

您的错误是告诉您您正在尝试访问“标题”,但是您认为附加到该对象的对象没有任何价值。您可以使用:

来克服错误
if([name of the variable])
    [name of the variable].title;

因此,如果您的变量称为book:

if(book) // Checks if book is null
    console.log(book.title); // Only access the title if the book is not null
相关问题