В приведенном ниже коде, когда я возвращаю объект класса в функции getServerSideProps
через реквизит, в функции страницы переменная не определена, как и в приведенном ниже коде.
export default function cars(obj){
return <h1>counter: {obj.counter}</h1> // obj is undefined, why??
}
export async function getServerSideProps({req,res}){
class Counter{
constructor(){
this.counter = 22
}
}
var counter = new Counter()
return {
props:
{
obj:JSON.stringify(counter)
}
}
}
Я ожидал, что параметр страницы obj будет иметь счетчик объектов и не будет неопределенным.
export default function cars(props){
return <h1>counter: {JSON.parse(props.obj).counter}</h1>
}
решение этой проблемы:
export default function cars({obj}){ // <-- here you have to get the member of the dictionary
return <h1>counter: {obj.counter}</h1> // obj is undefined, why??
}
export async function getServerSideProps({req,res}){
class Counter{
constructor(){
this.counter = 22
}
}
var counter = new Counter()
return {
props:
{
obj:JSON.stringify(counter)
}
}
}
Компоненты React получают объект, содержащий свойства. Подпись вашего компонента должна быть
export default function Cars({ obj }){ ... }
.