简体   繁体   English

如何将组件的值传递给另一个组件

[英]How to get value of a component to another component

I am creating a Project where I need to get value of a component state value to another component.我正在创建一个项目,我需要在其中获取组件 state 值的值到另一个组件。

How can I get the value?我怎样才能得到价值?

Information信息

  1. Both are functional component.两者都是功能组件。
  2. I need to send data from A (state) to B(state).我需要将数据从 A(状态)发送到 B(状态)。
  3. A state data are set from react dropdown menu.Which is a button. state 数据是从react dropdown中设置的。这是一个按钮。
  4. I don't use Link or Route to A dropdown that's why I can't get it with useParams()我不使用Link or Route to A下拉列表,这就是为什么我无法使用useParams()获取它
  5. I need to set value in B component which will fetch data with passing language.我需要在B组件中设置值,它将使用传递的语言获取数据。
  6. I have import all needed things & don't have any warnings & error.我已经导入了所有需要的东西并且没有任何警告和错误。

Code of component A A组份代号

  1. Send value from this language state to B将此language的值 state 发送到B
const A = () => {
    const [language, setLanguage] = useState('en');
    
    return (
        <Navbar expand="xl" bg='light' expand={false}>
            <Container>
                <DropdownButton id="dropdown-basic-button" title={<MdOutlineLanguage />}>
                    <Dropdown.Item as="button" onClick={() => setLanguage('en')}>English</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('ar')}>العربية</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('bn')}>বাংলা</Dropdown.Item>
                </DropdownButton>
            </Container>
        </Navbar>
    )
};

export default A

Code of Component B B组份代号

  1. I need to get here A state value & set it to B state. Then pass to useGetDataQuery & fetch data.我需要在此处获取A state 值并将其设置为B state。然后传递给useGetDataQuery并获取数据。
const B = () => {
    let [language, setLanguage] = useState('en')
    const { data } = useGetDataQuery({language })
    
    return (
        <>
            
        </>
    )
}
export default B

Redux Section Redux科

I'm using readux & @reduxjs/toolkit to store fetch data.我正在使用readux & @reduxjs/toolkit来存储获取数据。 Can I store my language data to here.我可以将我的language数据存储到这里吗? Than how can get to from anywhere of my component.比起如何从我的组件的任何地方到达。

  1. react-rotuer-dom v6 react-rotuer-dom v6
export default configureStore({
    reducer: {
        [dataOne.reducerPath]: dataOne.reducer,
        [data2.reducerPath]: dataTwo.reducer,
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat([dataOne.middleware, dataTwo.middleware]),

})

Maybe instead of using useState , you can use a global state by using useContext because I think your language will be use on several places as request body and of course to edit the state value, you can combine it with useReducer .也许不使用useState ,您可以通过使用useContext 使用全局 state因为我认为您的language将在多个地方用作请求正文,当然要编辑 state 值,您可以将它与useReducer结合使用。

// UPDATE // UPDATE

working code: https://codesandbox.io/s/sleepy-monad-21wnc工作代码: https://codesandbox.io/s/sleepy-monad-21wnc

MyContext

import { useReducer, useContext, createContext } from "react";

const initialValue = {
  language: "id"
  // other: "value",
};

const AppContext = createContext(initialValue);

const AppReducer = (state, action) => {
  switch (action.type) {
    case "CHANGE_LANGUAGE":
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
};

const MyContext = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialValue);
  return (
    <AppContext.Provider value={[state, dispatch]}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppContext = () => useContext(AppContext);
export default MyContext;

this is the context and reducer component later on use in App.js这是稍后在App.js中使用的contextreducer组件

App.js

import A from "./A";
import B from "./B";
import MyContext from "./MyContext";
import "./styles.css";

export default function App() {
  return (
    <MyContext>
      <div className="App">
        <A />
        <B />
      </div>
    </MyContext>
  );
}

A.js

import { useAppContext } from "./MyContext";

const A = () => {
  const [globalState, dispatch] = useAppContext();

  const onChange = (e) => {
    dispatch({
      type: "CHANGE_LANGUAGE",
      payload: {
        [e.target.name]: e.target.value
      }
    });
  };

  return (
    <>
      <p>Start Of Component A </p>
      <input value={globalState.language} name="language" onChange={onChange} />
      <p>End Of Component A </p>
    </>
  );
};

export default A;

B.js

import { useAppContext } from "./MyContext";

const B = () => {
  const [globalState, dispatch] = useAppContext();

  return (
    <>
      <p>Start Of Component B </p>
      <h2>Language Val : {globalState.language}</h2>
      <p>End Of Component B </p>
    </>
  );
};

export default B;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM