简体   繁体   English

State 在 axios 请求后未更新

[英]State not being updated after axios request

I previously had this code that made a get request via Axios to my local host to fetch data from an API.我之前有此代码通过 Axios 向我的本地主机发出获取请求,以从 API 获取数据。

export default function BasicTable() {
  const [orders, getOrders] = useState(null);
  useEffect(() => {
     fetchOrders();
  }, []);
  const fetchOrders = () => {
  axios.get("http://localhost:3000/orders").then((response) => {
      const res_orders = response.data.Items;
      console.log(res_orders);
      getOrders(res_orders);
  })
  .catch(error => console.error(`Error: ${error}`));

  }
  return (

      <div className="Table">
      <h3>Recent Orders</h3>  
        <TableContainer
          component={Paper}
          style={{ boxShadow: "0px 13px 20px 0px #80808029" }}
        >
          <Table sx={{ minWidth: 650 }} aria-label="simple table">
            <TableHead>
              <TableRow>
                <TableCell>Product</TableCell>
                <TableCell align="left">Tracking ID</TableCell>
                <TableCell align="left">Date</TableCell>
                <TableCell align="left">Customer</TableCell>
                <TableCell align="left">Company</TableCell>
                <TableCell align="left">Status</TableCell>
                <TableCell align="left">Quantity</TableCell>
                <TableCell align="left"></TableCell>
              </TableRow>
            </TableHead>
            <TableBody style={{ color: "white" }}>
            {orders && orders.map(order => (
              Object.keys(order.sales).map(sale => 
                <TableRow
                key={order.id}
               // sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
              >
                <TableCell component="th" scope="row">
                  {order.sales[sale].name}
                </TableCell>
                <TableCell align="left">{order.sales[sale].trackingid}</TableCell>
                <TableCell align="left">{order.orderplaced}</TableCell>
                <TableCell align="left">{order.name}</TableCell>
                <TableCell align="left">{order.company}</TableCell>
                <TableCell align="left">
                  <span className="status" style={makeStyle(order.sales[sale].status)}>{order.sales[sale].status}</span>
                </TableCell>
                <TableCell align="left">{order.sales[sale].sales}</TableCell>
                <TableCell align="left" className="Details">Details</TableCell>
              </TableRow>
              )))} 
         
            </TableBody>
          </Table>
        </TableContainer>
      </div>
  );
}

I changed the URL to my ec2 instance that was running the backend API I created.我将 URL 更改为运行我创建的后端 API 的 ec2 实例。 However, after changing it back to the localhost URL that I have running on a different port in my machine, I noticed that my orders state is undefined.但是,在将其更改回我在机器的不同端口上运行的本地主机 URL 后,我注意到我的订单 state 未定义。 It seems to be able retrieve the orders on the get request as I am able to print it out, but for some reason it seems as though the state never updates and thus my component does not render.它似乎能够检索 get 请求中的订单,因为我可以将其打印出来,但由于某种原因,state 似乎永远不会更新,因此我的组件不会呈现。

console output控制台 output

I've tried changing my fetch orders to an async function but still, the same result happened.我尝试将我的获取订单更改为异步 function 但仍然发生了相同的结果。

useEffect() is a side effect. useEffect() 是一个副作用。 Meaning react cycle checks it out after render.意思是反应周期在渲染后检查它。 what your doing is passing null to your initial state, which is then interprated by the render as null initially.您所做的是将 null 传递给您的初始 state,然后最初由渲染器将其解释为 null。

  1. change state to empty array instead of null, because you want to map it.将 state 更改为空数组而不是 null,因为您想要 map 它。

const [orders, getOrders] = useState([]); const [orders, getOrders] = useState([]);

  1. add 'orders' state as a dependency to useEffect, so that react cycle keeps track of it and renders again when it changes.添加 'orders' state 作为 useEffect 的依赖项,以便反应循环跟踪它并在它更改时再次呈现。

useEffect(() => { fetchOrders(); }, [orders]); useEffect(() => { fetchOrders(); }, [orders]);

3.in addition try to set conditional if orders is empty to render something different just in case 3.此外,如果订单为空,请尝试设置条件以呈现不同的内容,以防万一

  1. it's usually 'setOrders' not getOrders, but it's insignificant.它通常是 'setOrders' 而不是 getOrders,但它无关紧要。 You do you:-)你做你:-)

You should use this code instead of your code.您应该使用此代码而不是您的代码。 Set orders as blank array in initial state and later set orders using the prevState syntax like as I did.在初始 state 中将订单设置为空白数组,然后像我一样使用 prevState 语法设置订单。

const [orders, getOrders] = useState([]);
  useEffect(() => {
     fetchOrders();
  }, []);
  const fetchOrders = () => {
  axios.get("http://localhost:3000/orders").then((response) => {
      const res_orders = response.data.Items;
      console.log(res_orders);
      getOrders(prevState => (res_orders));
  })
  .catch(error => console.error(`Error: ${error}`));

}

I think this good approach for API calls...我认为 API 调用的这种好方法......

const fetchOrders =async () => {
     let response=await axios.get("http://localhost:3000/orders");
          getOrders(response.data.Items);
      }

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

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