【问题标题】:setState in parent component using parameter in child使用子组件中的参数在父组件中设置状态
【发布时间】:2020-11-28 10:35:03
【问题描述】:

我正在尝试从子组件调用 setList(useState 挂钩集),但反应检索错误: 类型错误 setList 不是函数

这里是父组件。我将 handleDrop 传递给 Box 组件:

import React, { memo, useState } from "react";
import { Dustbin } from "./Dustbin";
import { Box } from "./Box";
export const Container = memo(function Container() {
    const { list, setList } = useState();
    
    const handleDrop= (item)=>{
        console.log("dopped", item);
        setList(item);
    }

  return (
    <div>
      <div style={{ overflow: "hidden", clear: "both" }}>
        <Dustbin list={list} />
      </div>
      <div style={{ overflow: "hidden", clear: "both" }}>
        <Box name="Glass" handleDrop={handleDrop} />
        <Box name="Banana" handleDrop={handleDrop} />
        <Box name="Paper" handleDrop={handleDrop} />
      </div>
    </div>
  );
});

这里是 Box 组件:

import React from "react";
import { useDrag } from "react-dnd";
import { ItemTypes } from "./ItemTypes";
const style = {
  border: "1px dashed gray",
  backgroundColor: "white",
  padding: "0.5rem 1rem",
  marginRight: "1.5rem",
  marginBottom: "1.5rem",
  cursor: "move",
  float: "left"
};
export const Box = ({ name, handleDrop }) => {
  const [{ isDragging }, drag] = useDrag({
    item: { name, type: ItemTypes.BOX },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        handleDrop({pippo: item.name}); //here the call
        console.log(item);
      }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });
  const opacity = isDragging ? 0.4 : 1;
  return (
    <div ref={drag} style={{ ...style, opacity }}>
      {name}
    </div>
  );
};

我在这里错过了什么?

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    useState 返回一个数组而不是对象,

    而不是

    const { list, setList } = useState();
    

    const [list, setList ] = useState();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2018-04-29
      • 2019-09-07
      相关资源
      最近更新 更多