简体   繁体   English

如何访问另一个组件中的数据?

[英]How can I access data in another component?

I'm sorry if my question is too ridiculous, because I'm new to programming.如果我的问题太荒谬,我很抱歉,因为我是编程新手。

I created a project with React, I have 3 different components: navbar, sidebar and data.我用 React 创建了一个项目,我有 3 个不同的组件:导航栏、侧边栏和数据。

I received json data from an api using hooks in my data component.我使用数据组件中的钩子从 api 收到 json 数据。

 import { useEffect, useState } from "react"; export const Data = () => { const [data, setData] = useState(); useEffect(() => { fetch("https://jsonplaceholder.typicode.com/todos/1").then((response) => response.json()).then((json) => setData(json)); }, []); };

Now, how can I access the "data" state in the data component from other components?现在,如何从其他组件访问数据组件中的“数据”state?

I don't want to use Context api, because I've heard that it is only used in cases where the state affects all components, like authentication我不想使用上下文 api,因为我听说它仅用于 state 影响所有组件的情况,例如身份验证

thanks in advance for your help在此先感谢您的帮助

I have added few lines in your codesandbox.我在您的代码框中添加了几行。 I think this is same that you want to achieve我认为这与您想要实现的目标相同

codesandbox 密码箱

Thank you to everyone who helped me.感谢所有帮助过我的人。 Actually, I realized that the title is not correct.实际上,我意识到标题不正确。 What I wanted to do was to use the data brought outside the component inside the component.我想做的是在组件内部使用组件外部带来的数据。 I did this by creating custom hooks.我通过创建自定义钩子来做到这一点。 If anyone is curious, I leave the code below.如果有人好奇,我把代码留在下面。

 import { useEffect, useState } from "react"; export default function useData(id = 1) { const [data, setData] = useState([]); useEffect(() => { fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then((response) => response.json()).then((json) => setData(json)); }, []); return { data }; }

Then I import and use the useData hook I created in any component.然后我导入并使用我在任何组件中创建的 useData 挂钩。 (I'm not even sure it's called a hook.) Example: const {data} = useData(4) (我什至不确定它是否称为钩子。)示例: const {data} = useData(4)

You could maybe use the module.exports function in the data component and then just call it in the necessary components.您可以在数据组件中使用 module.exports function,然后在必要的组件中调用它。 For example:例如:

import { useEffect, useState } from "react";

export const Data = () => {
  const [data, setData] = useState();
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);
};

module.exports = data;

Then in the navbar component for example you call it and use it where it is necessary:然后在导航栏组件中,例如你调用它并在需要的地方使用它:

const Navbar = () => {
const data = require(../Data)
...
...
...
}

Hope it helps.希望能帮助到你。

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

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