【问题标题】:How to call function in a different component in React.js?如何在 React.js 的不同组件中调用函数?
【发布时间】:2023-01-23 14:58:15
【问题描述】:

我有两个组成部分。

显示单选按钮的 DropDownForRoomChangeCondo.js js。 DiscoverCondoRoom.js 显示 DropDownForRoomChangeCondo.js。

我想要实现的是在 DropDownForRoomChangeCondo.js 中,当使用 handleChange 向后端发送请求时(切换单选按钮时)我想通过调用 getDevices() 来更改屏幕显示;在 DiscoverCondoRoom.js 中。 (由于切换单选按钮时安装设备的房间的分配发生变化,因此我想更新显示)

问题/错误消息

当前,使用 handleChange 向后端发送请求时(切换单选按钮时)不会发生显示更新。

DropDownForRoomChangeCondo.js

import Dropdown from 'react-bootstrap/Dropdown';

const DropDownForRoomChangeCondo = (item) => {
  const history = useHistory();
  const [devices, setDevices] = useState([]);

  const handleChange = e => {
    setVal(e.target.name);
    setDeviceRoomName(e.target.name);
  }


  const setDeviceRoomName = async(data) => {
    console.log("Body sent to server", {
      attributes: 
      [
        {
          entity_id : item.item.entity_id, 
          room_name: data
        }
    ]
    })
    await axios.post('xxx.com',
      {
          attributes: 
          [
            {
              entity_id : item.item.entity_id, 
              room_name: data
            }
        ]
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Set Device Room Name!');
        getDevices();
      })
      .catch(err => {
        console.log(err);
        console.log('Missed Set Device Room Name!');
      });
  }

  const getDevices = async(data) => {
    await axios.get('xxx.com',
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log(result.data)
        console.log("bbbbbbbbbbb")
        setDevices(result.data.attributes);  
      })
      .catch(err => {
        console.log(err);
      });
  }


  const keys = [
    "camera",
    "climate",
    "cover",
    "light",
    "lock",
    "sensor",
    "switch",
  ];

  const entities = keys
    .map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
    .flat();

  const roomNames = [...new Set(entities.map((entity) => entity.room_name))];


  const [val, setVal] = useState(item.item.room_name);
  console.log(val)
  console.log(typeof(val))


  const CustomToggle = React.forwardRef(({ children, onClick }, ref) => (
    <a
    href=""
    ref={ref}
    onClick={(e) => {
      e.preventDefault();
      onClick(e);
    }}
  >
    {children}
    <img className="ic_edit" src={ic_edit} />
  </a>
  ));

useEffect(() => {
  getDevices();
},[]);


  return (
    <>

                    <div className="">
                    <p>{item.item.room_name}</p>
                    <Dropdown className="room_change_dropdown_top">

                    <Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components" />

                    <Dropdown.Menu className="room_change_dropdown">
                        <Dropdown.Item className="room_change_dropdown_item">
                          {roomNames.map((room_names, i) => (
                            <div className="flex_radio">
                              <input
                                className="room_change_radio"
                                type="radio"
                                value={room_names}
                                name={room_names}
                                onChange={handleChange}
                                checked={val === room_names}
                              />
                              <p className="drop_down_p">{room_names}</p>
                            </div>
                            ))}
                        </Dropdown.Item>
                      </Dropdown.Menu>
                    </Dropdown>
                    </div>

    </>
  );
}
export default DropDownForRoomChangeCondo;

发现CondoRoom.js

const DiscoverCondoRoom = () => {
  const history = useHistory();
  const [devices, setDevices] = useState([]);

  const getDevices = async(data) => {
    await axios.get('xxx.com',
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        setDevices(result.data.attributes);  
      })
      .catch(err => {
        console.log(err);
      });
  }
  
  useEffect(() => {
    getDevices();
  },[]);

  const lll = Object.keys(devices);
  const object_device_value = Object.values(devices).flat();



  const keys = [
    "camera",
    "climate",
    "cover",
    "light",
    "lock",
    "sensor",
    "switch",
  ];

  const entities = keys
    .map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
    .flat();

  const roomNames = [...new Set(entities.map((entity) => entity.room_name))];



  return (
    <>
        <div className="container condo_container">
                    {entities.map((entity, i) => (
                            <DropDownForRoomChangeCondo item={entity} />
                    ))}
        </div>
    </>
  );
}
};


export default DiscoverCondoRoom;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要将 getDevices 方法作为道具传递给下拉组件。

    <DropDownForRoomChangeCondo item={entity} getDevices={getDevices} />
    

    然后在您的 DropDown 组件中,通过调用 props.getDevices() 在您想要的位置调用 getDevices 方法

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多