在 nextjs 中将 props 从一个页面传递到另一个页面

Ali*_*aie 4 javascript reactjs next.js react-props

我有一个虚拟项目。在我的项目中,我有两个页面。(test1 和 test2)我想将一个道具从 page1 传递到 page2。我知道我可以使用 useRouter 钩子,但我不想将此道具设置为查询字符串。在我的 test1 页面中,我有一个颜色变量。这是常量,并且有一个黄色值。我想在我的 page2 中使用此颜色作为道具(props.color),这是我的 test1 页面

import React from 'react';
const Test1 = props => {
   const color='yellow';
    return (
        <div>
            test1
        </div>
    );
};

export default Test1;
Run Code Online (Sandbox Code Playgroud)

这是我的 test2 页面

import React from 'react';

const Test2 = props => {
    return (
        <div>
            Your color is {props.color}
        </div>
    );
};


export default Test2;
Run Code Online (Sandbox Code Playgroud)

小智 5

也许有太多的方法,但对我来说,我认为你可以使用localStorage

例子:

//in your test1 
//foo is the key, bar is the value
localStorage.setItem("foo", "bar")

//in your test 2 you can get the bar by using foo key
const bar = localStorage.setItem("foo", "bar")

console.log(bar)// bar
Run Code Online (Sandbox Code Playgroud)

这里有一个名为useLocalStorage的钩子,您可以使用它或自定义您自己的钩子。