简体   繁体   English

在 setState 中响应推送 Api 响应

[英]React push Api response in the setState

in my EventForm i have this const, this is a dialog form在我的 EventForm 中我有这个常量,这是一个对话框表单

this is my EventForm.js这是我的 EventForm.js

const EventForm = (props) => {

const { setOpenPopup, records, setRecords, setMessage, setOpenSnackbar } = props

const addEvent = () => {
    axios.post('https://jsonplaceholder.typicode.com/events', (event)
      .then(resp => {
        console.log(resp.data)
        const newData = [{
          title: resp.data.name,
          start: resp.data.starts_at,
          end:  resp.data.ends_at
        }]
        setRecords([{ ...records, newData}])
        //
        setOpenPopup(false)
        setMessage('New Event added')
        setOpenSnackbar(true)
      })
      .catch([])
  }



export default EventForm
EventForm.propTypes = {
  setOpenPopup: PropTypes.func,
  records: PropTypes.array,
  setRecords: PropTypes.func,
  setMessage: PropTypes.func,
  setOpenSnackbar: PropTypes.func
}

}

in my EventTable.js在我的 EventTable.js

 const [records, setRecords] = useState([]);

useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/events')
  .then(resp => {
    const newData = resp.data.map((item) => ({
      title: item.name,
      start: item.starts_at,
      end:  item.ends_at
    }))
    setRecords(newData)
  })
  .catch(resp => console.log(resp))
  }, [])



fullcalendar...
 events={records}

im trying to push the API post response to my setRecords.我试图将 API 帖子回复推送到我的 setRecords。 so when the dialog form close it will not use the GET response.所以当对话框关闭时,它不会使用 GET 响应。 ill just get the new record and render to my view生病只是获得新记录并呈现到我的视野

but im getting an error:但我收到一个错误:

Unhanded Rejection (TypeError): setRecords is not a function未经处理的拒绝(TypeError):setRecords 不是 function

在此处输入图像描述

I suspect you are using React Hooks.我怀疑你正在使用 React Hooks。 Make sure that your records state looks like this确保您的records state 看起来像这样

const [records, setRecords] = useState([]);

In your axios request, it looks like that you are trying to spread the values of records which is an array to an object.在您的axios请求中,您似乎正在尝试将作为数组的记录的值传播到 object。 I'd suggest refactoring this to something like this.我建议将其重构为这样的东西。 Instead of trying to spread an array into the object, take the previous state and merge it with the new one.与其尝试将数组传播到 object 中,不如取之前的 state 并将其与新的合并。

setRecords(prevRecords => [...prevRecords, ...newData])

Here's an example using React Hooks how the component could look like这是一个使用 React Hooks 的示例,该组件的外观如何

import React from "react";
import axios from "axios";

const MyComponent = ({
  setOpenPopup,
  records,
  setRecords,
  setMessage,
  setOpenSnackbar
}) => {
  const addEvent = () => {
    axios
      .post("https://jsonplaceholder.typicode.com/events", event) // Make sure this is defined somewhere
      .then((resp) => {
        const { name, starts_at, ends_at } = resp.data;
        const newData = [
          {
            title: name,
            start: starts_at,
            end: ends_at
          }
        ];

        setRecords((prevRecords) => [...prevRecords, ...newData]);
        setOpenPopup(false);
        setMessage("New Event added");
        setOpenSnackbar(true);
      })
      .catch([]);
  };

  return (
    <div>
      <button onClick={addEvent}>Click me </button>
    </div>
  );
};

export default MyComponent;

If you are not using React Hooks and use Class components, then make sure that you pass setRecords to your component in props.如果您没有使用 React Hooks 并使用 Class 组件,请确保您将setRecords传递给 props 中的组件。 Plus, in your props destructuring, make sure you add this to the props, otherwise, it can lead to unwanted behaviour.另外,在你的 props 解构中,确保你将this添加到 props 中,否则,它可能会导致不需要的行为。 Also, move your request function out of the render method and destructure values from the props that you need inside the function.此外,将您的请求 function 移出render方法,并从 function 中所需的道具中解构值。 I've also noticed that your axios syntax was incorrect (forgot to close after the event) so I fixed that as well.我还注意到您的axios语法不正确(事件发生后忘记关闭)所以我也修复了它。 Here's an example of how you can improve it.这是一个如何改进它的示例。

import React from "react";
import axios from "axios";

class MyComponent extends React.Component {
  addEvent = () => {
    const {
      setOpenPopup,
      setRecords,
      setMessage,
      setOpenSnackbar
    } = this.props;

    axios
      .post("https://jsonplaceholder.typicode.com/events", event)
      .then((resp) => {
        console.log(resp.data);
        const newData = [
          {
            title: resp.data.name,
            start: resp.data.starts_at,
            end: resp.data.ends_at
          }
        ];
        setRecords((prevRecords) => [...prevRecords, ...newData]);
        //
        setOpenPopup(false);
        setMessage("New Event added");
        setOpenSnackbar(true);
      })
      .catch([]);
  };

  render() {
    return (
      <div>
        <button onClick={() => this.addEvent()}>Click me</button>
      </div>
    );
  }
}

export default MyComponent;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM