reactjs - 根据 props 状态进行条件重定向

标签 reactjs react-router

如果 props.fields 的长度为零,我想重定向页面。但问题是它被渲染了两次,所以当它为空时,它会被重定向并且不会等待第二次。 我是 React 新手,如果有人能帮助我,那就太好了。我花了几个小时来解决这个问题。

import React, { Component, useEffect, useState } from 'react'
import Field from './field'
import {Redirect} from 'react-router-dom'





export default function FieldList(props) {

    const [redirect,setRedirect] = useState(false);
    useEffect(()=>{
        if(props.fields.length===0) {
            setRedirect(true)
        }
        else
            setRedirect(false)
    },[props.fields])
    
         return (
                <div>
                <h1 style={{textAlign:"center", margin:"20px 0"}}>{props.text}</h1>
                
                <div className='field-list'>
                {props.fields.map((name) => (
                    <Field name={name}  />
                ))}
                </div>
                {redirect && <Redirect to={'/'} />}
            </div>
            )
        
}

最佳答案

您可以使用自定义浏览器历史记录或使用 react-router-dom 的 useHistory Hook 来代替 Redirect

使用useHistory钩子(Hook)

import {useHistory} from 'react-router-dom'

然后在useEffect

   useEffect(()=>{
       if(props.fields.length===0) {
        useHistory().push('/')
        }
      },[props?.fields]
    )

如果您不想使用它,可以按照以下步骤创建自定义浏览器历史记录

首先创建一个文件并将其命名为History.js

添加这行代码

import { createBrowserHistory } from "history";
export default createBrowserHistory(); 

然后将其导入到文件中

  import history from "FILE_PATH"

   useEffect(()=>{
       if(props.fields.length===0) {
        history.push('/')
        }
      }
    )

关于reactjs - 根据 props 状态进行条件重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65964559/

相关文章:

javascript - react : what happens to a function when component stop being rendered

javascript - 保存动态加载的网页

javascript - 按钮输入类型提交不在 React 中使用 React Router 提交

javascript - react 子嵌套路由

reactjs - 当我部署到 Google App Engine 时,我的 React 前端没有改变

javascript - React Redux 不更新状态

javascript - 需要说明 : is it correct to return an array from a stateless component in React?

html - 防止React-router-dom刷新页面并重置点击时输入的信息

javascript - 在 ReactJs 中使用 react-router 获取事件路由

reactjs - History.push() 更新浏览器中的 URL,但不会呈现适当的组件(重定向也不起作用)