【问题标题】:NextJS access a variable from another componentNextJS 从另一个组件访问变量
【发布时间】:2022-01-20 21:39:23
【问题描述】:

我在组件中有一个变量。我希望能够在另一个组件中访问这个变量。 我使用 NextJS。

我该怎么办?

代码:

组件/Question.js

import { useState } from "react";

function Questions() {

    const [question, setQuestion] = useState("")

    const handleChange = event => {
        const target = event.target
        const name = target.name
        const value = target.value
        setQuestion(value)
    }
    ...

pages/jeux/test.js

const Game = (index) => {
   // I want have acces at the 'question' variable
   //console.log(question)

   return (
       <div>
           <p className="text-white">{index.index.title}</p>
       </div>
   )
}

【问题讨论】:

  • 你也可以使用RouteruseRouter,你拥有每个组件的每个props的所有props
  • 请问您有例子吗?

标签: reactjs next.js components


【解决方案1】:

你需要使用像 Redux(或 Redux Toolkit!)这样的全局状态管理,或者使用 React Context 来共享变量。

我比较熟悉redux toolkit(简称RTK)。在 RTK 中,您需要创建一个切片来管理一组特定的状态。

例如,假设您的问题是针对测验应用程序的,因此使用 RTK,您可以像这样创建测验切片

quizSlize.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
   questions: [] // your initial questions
};

const quizSlice = createSlice({
  name: "quiz",
  initialState // this is equal to initialState: initialState,
  reducers: { // reducers are functions to mutate the state
    resetState: () => initialState,
    setQuestions: (state, action) => {
      state.questions = action.payload
    },
  },
});

export const _quiz = quizSlice.actions; //_quiz will be the object that stores all your reducers
export const $quiz = ({ quiz }) => quiz; //$quiz will be the object that stores all your variables
export default quizSlice.reducer;

创建切片后,您可以在任何组件中使用它们(当然是在应用程序中设置后)

使用您的示例:

import {useDispatch, useSelector} from 'react-redux'
import {$quiz, _quiz} from './quizSlice'

function Questions() {
    const dispatch = useDispatch() // this is used to call the reducer
    const {question} = useState($quiz) // your variable

    const handleChange = event => {
        const target = event.target
        const name = target.name
        const value = target.value
        dispatch(_quiz.setQuestion(value))
    }
    ...
import {useSelector} from 'react-redux'
import {$quiz} from './quizSlice'

const Game = (index) => {
   // I want have acces at the 'question' variable
   const {question} = useSelector($quiz) // your variable
   //console.log(question)

   return (
       <div>
           <p className="text-white">{index.index.title}</p>
       </div>
   )
}

希望这会有所帮助。有关如何在您的应用中设置 RTK,您可以前往 Redux 工具包了解如何设置,或查找示例应用

【讨论】:

  • 对于这么简单的任务来说太过分了。
  • 谢谢你的帮助,我想我会使用 ReactContext
【解决方案2】:

作为反应只是通过道具发送你的变量

const passTheData = {}

<YourComponent data={passTheData} />

然后在你的组件中:

function YourComponent({data}){
  console.log(data)
}

【讨论】:

  • 嗯,好吧,但是用我的代码,我把信息放在哪里?
  • ```js const Game = ({index, question})=>{ // do ce que tu veux avec la question }
【解决方案3】:
import React, {useState} from "react"

const Game = ({theBigQuestion}) =>{
  console.log(theBigQuestion)
}

const Question = () =>{
  const [question, setQuestion] = useState("")
  const theQuestion = "C'est quoi la couleur de ton slip?"
  const handleChange = ()=>{
    setQuestion(theQuestion)
  }

  return (
    <Game theBigQuestion={question} />
  )
}

类似的东西

【讨论】:

  • 如果我这样做,我可以在 1 个文件中使用它,不是吗?
  • 但在我的示例中,变量theBigQuestion 将仅在游戏组件中可用。如果你想将它传递给其他地方,你最好使用useContext 或者只是调用组件并将相同的变量传递给它等等
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2016-09-16
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多