简体   繁体   English

如何使用反应钩子将对象数组从子组件发送到父组件并存储在父对象中?

[英]How to send array of objects data from child component to parent component and store in the parent object using react hooks?

This is my parent component js file...这是我的父组件js文件...

import React, { useContext, useState } from "react";
import TaskListContextProvider from "./TaskListContext";
import TaskList from "./TaskList";
import TaskForm from "./TaskForm";

const AddMenu = () => {
  const [menu, setMenu] = useState({
    menuName: "",
    tag: "",
    price: "",
    menuItem: ""
  });


  const addMenu = (e) => {
    const { name, value } = e.target;
    setMenu((preValue) => {
      return {
        ...preValue,
        [name]: value,
      };
    });
    
  };

   //function to recieve data from child component
    const addList=(data)=> {
    setMenu([...data,{menuItem:data}]);
   };

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(menu);
  };

  return (
        <div className="form-row">
          <div className="form-group">
            <input
              type="text"
              name="menuName"
              onChange={addMenu}
              value={menu.menuName}
            />
          </div>
          <div className="form-group">
            <input
              type="text"
              name="tag"
              onChange={addMenu}
              value={menu.tag}
            />
          </div>
          <div className="form-group">
            <div className="main">
              <TaskListContextProvider addList={addList}>
                <TaskForm />
                <TaskList />
              </TaskListContextProvider>
            </div>
          </div>
          <div>
            <input
              type="number"
              name="price"
              onChange={addMenu}
              value={menu.price}
            />
          </div>
        </div>
        <button
          type="submit"
          onClick={onSubmit}
        >
          Save
        </button>
  );
};

export default AddMenu;

This is my child component js file...这是我的子组件js文件...

import uuid from 'uuid'

export const TaskListContext = createContext()

const TaskListContextProvider = props => {
  const initialState = JSON.parse(localStorage.getItem('tasks')) || []
  
  const [editItem, setEditItem] = useState(null)
  const [tasks, setTasks] = useState(initialState)
  
// call-back function...
//   const sendData=()=>{
//     props.addList(tasks);
//   }
//   sendData();

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks))
    console.log(tasks);
    props.addList(tasks);
  }, [tasks])

    
  // Add tasks
  const addTask = title => {
    setTasks([...tasks, { title, id: uuid() }]) 
  }
  
  // Remove tasks
  const removeTask = id => {
    setTasks(tasks.filter(task => task.id !== id))
  }
  
  // Clear tasks
  const clearList = () => {
    setTasks([])
  }
  
  // Find task
  const findItem = id => {
    const item = tasks.find(task => task.id === id)
    setEditItem(item)
  }

  // Edit task
  const editTask = (title, id) => {
    const newTasks = tasks.map(task => (task.id === id ? { title, id } : task))
    
    console.log(newTasks)

    setTasks(newTasks)
    setEditItem(null)
  }

  return (
    <TaskListContext.Provider
      value={{
        tasks,
        addTask,
        removeTask,
        clearList,
        findItem,
        editTask,
        editItem
      }}
    >
      {props.children}
    </TaskListContext.Provider>
  )
}

export default TaskListContextProvider 

My question : How to send child component "tasks" variable data which contains array of objects to parent component and store them into object "menuItem" , so whenever i click on the save button it should display menu on the console??我的问题:如何将包含对象数组的子组件“任务”变量数据发送到父组件并将它们存储到对象“menuItem”中,所以每当我点击保存按钮时,它应该在控制台上显示菜单?

you can do this ...你可以这样做 ...

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks))
    props.addList(tasks);
  }, [tasks])

here right after setting the tasks into local storage you can send the data to parent.在将任务设置到本地存储后,您可以立即将数据发送给父级。

暂无
暂无

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

相关问题 如何在反应中将数组从子组件发送到父组件? - How to send an array from child component to parent component in react? 如何在反应中将对象数组从父组件传递到子组件 - How to pass Array of Objects from Parent Component to Child Component in react React中如何将数据从子组件发送到父组件 - How to send data from a child component to parent component in React 需要将 Checkbox Filtered Data from Child Component 发送到 Parent Component:React Hooks,Redux - Need to send the checkbox Filtered Data from Child Component to Parent Component : React Hooks, Redux 如何在React中将多个数据作为对象从子组件发送到父组件? - How can i send multiple data as an object to parent component from child component in React? 如何正确地将数组从父 React 类组件状态传递给使用钩子编写的子组件? - How to properly pass an array from a parent React class component state to a child component written with hooks? 将数据从子组件传递到父组件/React 钩子 - Passing data from child to parent component / React hooks 如何使用 React Hooks 从子组件 onClick() 触发父组件中的事件? - How to trigger an event in Parent Component from Child Component onClick() using React Hooks? 在React JS中将数据从子组件发送到父组件 - Send data from child component to parent component in react js 将数据从子组件发送到父组件 - Send Data from Child Component To Parent Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM