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

问题描述

这是我的父组件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;

这是我的子组件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 

我的问题:如何将包含对象数组的子组件“任务”变量数据发送到父组件并将其存储到对象“ menuItem”中,因此每当我单击保存按钮时,它都应在控制台上显示菜单

解决方法

您可以执行此操作...

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

在将任务设置到本地存储之后,您可以在此处将数据发送给父级。