最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - You should call navigate() in a React.useEffect(), not when your component is first rendered - Stack Overflow

programmeradmin3浏览0评论

I am new to ReactJS. On Initial Load of Page, I want to check if the state is null, then I want to redirect to another login Page

Here's the Component Code:

export default function Addblousesalwar() {
  const navigate = useNavigate();
  const { state } = useLocation();
  console.log(state)   //null
  if(state === null || state === undefined){
    navigate("/login")
  }

But It shows error:

You should call navigate() in a React.useEffect(), not when your ponent is first rendered.

I tried via useEffect also. But the useEffect doesn't get executed.

useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);



useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);

I tried this also

 useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, [state]);

This useeffect also not triggering Please Help me with some solutions

I am new to ReactJS. On Initial Load of Page, I want to check if the state is null, then I want to redirect to another login Page

Here's the Component Code:

export default function Addblousesalwar() {
  const navigate = useNavigate();
  const { state } = useLocation();
  console.log(state)   //null
  if(state === null || state === undefined){
    navigate("/login")
  }

But It shows error:

You should call navigate() in a React.useEffect(), not when your ponent is first rendered.

I tried via useEffect also. But the useEffect doesn't get executed.

useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);



useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);

I tried this also

 useEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, [state]);

This useeffect also not triggering Please Help me with some solutions

Share Improve this question edited Nov 30, 2021 at 7:41 rafekas asked Nov 30, 2021 at 7:27 rafekasrafekas 2511 gold badge3 silver badges6 bronze badges 4
  • Use console.log(state) to debug what it is – Lin Du Commented Nov 30, 2021 at 7:33
  • The useEffect hook is guaranteed to trigger the callback at least once when the ponent mounts. What isn't working, the navigation? Check the state value in the effect callback to see why the condition is not met. Also, Addblousesalwar doesn't appear to be a React function ponent or custom hook so it can't use React hooks anyway. – Drew Reese Commented Nov 30, 2021 at 7:34
  • state is null – rafekas Commented Nov 30, 2021 at 7:37
  • Think you could create a running codesandbox that reproduces this navigation/mounting issue that we could inspect and debug live? – Drew Reese Commented Nov 30, 2021 at 7:43
Add a ment  | 

5 Answers 5

Reset to default 3

As mentioned in the ments, you should really provide a codesandbox or at least more code.

That being said, I'm gonna guess that 'state' is not undefined nor is it null, it's an [] (that's usually what it's defaulted to const [state, setState] = useState([]) ) and that's why you think it's not working.

try

useEffect(() => {
    if(!state.length){
      navigate("/")
    }
  }, []); 

you should use useEffect after all asynchronous function, here the example:

const userInfo = localStorage.getItem('user-info');
    
async function signUp() 
{
    let item = {name, password, email};
    console.warn(item);
    let result = await fetch("http://127.0.0.1:8000/api/register",{
            method: 'POST',
            body: JSON.stringify(item),
            headers: {
                "content-type": 'application/json',
                "Accept": 'application/json'}
        })
    result  = await result.json();
    console.warn('result', result);
    localStorage.setItem("user-info",JSON.stringify(result));
    navigate("/add");
}

useEffect(() => {
    if (userInfo){
     navigate("/add")   
    }
},[])
useEffect(() => {
 if(state == null || state == undefined){
      navigate("/")
    }
  }, [state, navigate]);

there is
export default function Addblousesalwar() {
    const navigate = useNavigate();
    const { state } = useLocation();

    //I used useLayoutEffect instead of useEffect and the below turned into warning instead of an error

    //You should call navigate() in a React.useEffect(), not when your ponent is first rendered.

     useLayoutEffect(() => {
    if(state === null || state === undefined){
      navigate("/")
    }
  }, []);
 }

Try adding "state" and "navigate" to your "useEffect" dependencies. Maybe it will solve your problem.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论