[英]How to pass data from one component to another in react without re-render or jsx like from a function using functional components
I am new to react and I am not getting any answers on this.我是新来的反应,我没有得到任何答案。
I want to pass data from one functional component to another in react.我想在反应中将数据从一个功能组件传递到另一个功能组件。 However I do not want to render the child component.
但是我不想渲染子组件。 I just want to pass the data from one component to another.
我只想将数据从一个组件传递到另一个组件。 How do I achieve this?
我如何实现这一目标?
Please help请帮忙
There has to be a way to do this.必须有办法做到这一点。
Simply do not return anything from the functional component that you don't want to render.只需不要从功能组件中返回您不想呈现的任何内容。
A functional component renders whatever the return
statement returns.功能组件呈现
return
语句返回的任何内容。
If I understand you correct, you want to pass data as prop to child component and do not want it to be re-rendered.如果我理解你是正确的,你想将数据作为道具传递给子组件并且不希望它被重新渲染。
Let's define a functional component using React.memo so that it will not be re-rendered unless its props changes.让我们使用 React.memo 定义一个函数式组件,这样它就不会被重新渲染,除非它的 props 发生变化。
mine.js我的.js
import React from "react";
const Mine = React.memo((props) => {
console.log('renders')
return <h1>HI!</h1>
})
Now we call it inside our app现在我们在我们的应用程序中调用它
App.js应用程序.js
import React, { useState, useMemo } from "react";
export default function App() {
const arr = useMemo(() => [1,2,3], []);
const [counter, setCounter] = useState(0);
const onClickHandler = (e) => {
let c = counter;
setCounter(c+1);
}
return (
<div className="App">
<h1>{counter}</h1>
<button onClick={onClickHandler}>Click</button>
<Mine arr={arr} />
</div>
);
}
If you take your attention to console.log, you are going to see that component Mine will not be re-rendered even the parent component state changes when you press the button.如果您注意console.log,您将看到即使父组件state 在您按下按钮时发生更改,组件Mine 也不会重新渲染。 Pressing the button will cause a re-render on parent component, app, but child component will stay same.
按下按钮将导致父组件应用程序重新渲染,但子组件将保持不变。 We passed a prop called arr to the child component and we wrapped it with useMemo.
我们将一个名为 arr 的 prop 传递给子组件,并用 useMemo 包装它。 If you remove useMemo, you will see that it will cause child component, mine, to be re-rendered.
如果你删除 useMemo,你会看到它会导致我的子组件被重新渲染。 So we memoized data.
所以我们记住了数据。
I guess this is what you want.我想这就是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.