不重定向到React JS中指定的路径

时间:2020-05-03 14:54:10

标签: reactjs redirect react-redux react-router react-router-dom

rhazdon/hugo-theme-hello-friend-ng

它位于if语句内,但不会重定向到指定的路径。

4 个答案:

答案 0 :(得分:0)

您想使用public class OptMsgTypeCreateViewModel { public OptMsgTypeCreateViewModel() { OptMsgType = new OptMsgType(); } public OptMsgType OptMsgType { get; set; } public IEnumerable<SelectListItem> OptStatuses { get; set; } } 而不是state

props

答案 1 :(得分:0)

<Redirect>组件仅在渲染时返回时才可以工作。您没有显示代码所在位置的上下文,但是由于它是异步的,因此无法呈现任何内容。

您有两个选择:

1)设置状态,导致重新渲染,然后渲染<Redirect>

const Example = () => {
  const [redirectTo, setRedirectTo] = useState(null);
  useEffect(() => {
    AuthService.createDesigns(data).then(res => {
      if (res.data.status === "success") {
        const designId = res.data.data.id
        setRedirectTo({
          pathname: `${match.url}/${designId}`,
          state: hoodieData
        })
      }
    });
  }, []);

  if (redirectTo) {
    return <Redirect to={redirectTo} />
  }

  // else, render the component as normal
}

2)或我愿意做的:使用history.replace代替<Redirect>组件

const history = useHistory();
useEffect(() => {
  AuthService.createDesigns(data).then(res => {
    if (res.data.status === "success") {
      const designId = res.data.data.id
      history.replace(`${match.url}/${designId}`, hoodieData);
    }
  });
}, []);

// render the component as normal

答案 2 :(得分:0)

您是否正在尝试通过api调用返回React JSX?这不是您应该重定向的方式。使用您的历史记录(如果您使用的是最新版本的React Router,请使用useHistory挂钩);

 AuthService.createDesigns(data).then(res => {
        if (res.data.status === "success") {
            const designId = res.data.data.id
            history.replace(`${match.url}/${designId}`, hoodieData);
           // return <Redirect to={{
             //   pathname: `${match.url}/${designId}`,
               // props: hoodieData
           // }} />
        }
        return true
    })

使用useHistory挂钩-

import { useHistory } from "react-router-dom";

AuthService.createDesigns(data).then(res => {
        if (res.data.status === "success") {
            const designId = res.data.data.id
            history.replace(`${match.url}/${designId}`, hoodieData); //or history.push
           // return <Redirect to={{
             //   pathname: `${match.url}/${designId}`,
               // props: hoodieData
           // }} />
        }
        return true
    })

答案 3 :(得分:0)

这有效

        AuthService.createDesigns(data).then(res => {
            if (res.data.status === "success") {
                const designId = res.data.data.id
                history.push({
                    pathname: `${match.url}/${designId}`,
                    state: hoodieData
                })
            }
            return true
        })

感谢您的帮助。

相关问题