简体   繁体   English

如何将更新数据发送到子组件。 反应

[英]How do I send updating data to a child component. React

If I have an object key values that we assume change due to some input.如果我有一个 object 键值,我们假设由于某些输入而发生变化。 How do I update the child component that takes those values and displays them.如何更新获取这些值并显示它们的子组件。 When I send the values as props to the child component they obviously don't update and stay as the initial value set in tempData.当我将值作为道具发送给子组件时,它们显然不会更新并保持为 tempData 中设置的初始值。 So how would I prompt the child props to resend or update?那么如何提示子道具重新发送或更新呢?

I already have functions that fetch the data and put it all into its places in the tempData object.我已经有函数可以获取数据并将其全部放入 tempData object 中的位置。 Am I going about this wrong by setting the data in an Object?我是否通过在 Object 中设置数据来解决这个问题?

 const Parent = () => { const tempData = { location: "", weather: "", temperature: "", }; return ( <> <System onChange={(value) => urlHandler(value)} /> <City onChange={(value) => setCity(value)} /> <Data location={tempData.location} weather={tempData.location} temperature={tempData.temperature} /> </> }; const Child = (props) => { return( <> <div>location: {props.location}</div> <div>temperature: {props.temperature}</div> </> ) };

React has no way to detect that you have mutated tempData so it won't re-render the element with the new data. React 无法检测到您已tempData ,因此它不会使用新数据重新渲染元素。

Store the data in the state instead.将数据存储在state中。 Using the state API to update the state will trigger a re-render.使用 state API 更新 state 将触发重新渲染。

This is covered in the React tutorial but that focuses on old-style class components.这在React 教程中有所介绍,但重点关注旧式 class 组件。 Modern code would use the useState hook in a function component instead.现代代码将在 function 组件中使用useState挂钩 This is also covered by the MDN React tutorial . MDN React 教程也涵盖了这一点。

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

相关问题 如何在 React 中将数据从子组件发送到父组件 - How do I send data from child component to parent component in React 如何将数组发送到 React 中的子组件? - How do I send an array to a child component in React? 我如何编写此类组件来响应功能组件。? - How can i write this class component to react functional component.? React 数据表组件。 如何动态 select 行 - React data table component. How to dynamically select rows 如何在React中将多个数据作为对象从子组件发送到父组件? - How can i send multiple data as an object to parent component from child component in React? React中如何将数据从子组件发送到父组件 - How to send data from a child component to parent component in React 如何将数据以及子组件发送到组件-JavaScript-react - how to send data as well as child component to a component - JavaScript - react 当父组件向子组件传递数据并渲染子组件时显示加载栏。 反应.JS - show loading bar when parent component pass data to and render child component. React.JS React:在子组件中更改了 state。 如何查看父组件的变化? - React: Changed state in Child component. How to see the change in parent component? 如何将数据传递给子组件? - How do I pass the data to the child component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM