微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将道具从页面传递到 nextjs 中的另一个页面

如何解决将道具从页面传递到 nextjs 中的另一个页面

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

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

export default Test1;

这是我的 test2 页面

import React from 'react';

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


export default Test2;

解决方法

Props 从父组件传递给它的子组件。您要问的是在兄弟组件(即页面)之间传递道具,我认为这没有直接的方法。也许您可以尝试使用 React 的 Context API,这样您的 Test2 就不会使用任何硬编码值。

,

也许有很多方法,但对我来说,我认为您可以使用 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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。