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

javascript - passing props from a page to another page in nextjs - Stack Overflow

programmeradmin7浏览0评论

i have a dummy project.in my project i have two pages.(test1 & test2) i want passing a prop from page1 to page2.i know that i can use useRouter hook but i don't want set this prop as a query string. in my test1 page i have a color variable.this is const and have a yellow value.i want use this color in my page2 as a prop(props.color) this is my test1 page

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

export default Test1;

i have a dummy project.in my project i have two pages.(test1 & test2) i want passing a prop from page1 to page2.i know that i can use useRouter hook but i don't want set this prop as a query string. in my test1 page i have a color variable.this is const and have a yellow value.i want use this color in my page2 as a prop(props.color) this is my test1 page

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

export default Test1;

and this is my test2 page

import React from 'react';

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


export default Test2;

Share Improve this question edited Jul 31, 2022 at 17:55 juliomalves 50.3k23 gold badges177 silver badges168 bronze badges asked Jul 19, 2021 at 18:00 Ali EhyaieAli Ehyaie 1,2604 gold badges14 silver badges33 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Maybe there are too may ways but for me, I think you can use localStorage.

Example:

//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.getItem("foo")

console.log(bar)// bar

And here is a hook called useLocalStorage You can use for that or customize your own.

Props are passed from a parent ponent to its child ponents. What you are asking is to pass props between sibling ponents (ie. page) which I don't think has a straightforward way to do so. Maybe you can try using React's Context API so that your Test2 is not using any hard-coded value.

You can also get data in second page by using getInitialProps after passing the params in Test1 page

Passing Params

import Link from "next/link";

<Link href={{ pathname: '/test2', query: { color: 'yellow' } }}><a>test2</a></Link>

Getting Params

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

Index.getInitialProps = async ({ query }) => {
  const {color} = query

  return {color}
}

hope this helps.

发布评论

评论列表(0)

  1. 暂无评论