【问题标题】:React: loop through array response does not workReact:循环遍历数组响应不起作用
【发布时间】:2020-02-12 14:51:56
【问题描述】:

我向 Express 服务器运行 axios get 请求以获取一些虚拟数据:

  customers = [
    { id: 1, firstName: "John" },
    { id: 2, firstName: "Brad" },
    { id: 3, firstName: "Mary" }
  ];

返回的数据由用户输入决定:如果用户输入“Brad”,返回的结果将是 { id: 2, firstName: "Brad" }。

由于某种原因,当我遍历返回的数据时,没有任何效果。查看 React Chrome 扩展,返回的状态如下:

{
  "firstName": "Brad",
  "id": 0,
  "customers": [],
  "res": []
}

因为我正在学习 React,所以我会把整个组件贴出来给你看,也许问题是我作为新手还没有看到的问题:

    class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      firstName: "",
      id: 0,
      customers: []
    };


      this.getName = this.getName.bind(this);

  }

     onChange = e => {
      e.preventDefault();
      this.setState({ firstName: e.target.value });
     };

    getName = e => {
     e.preventDefault();
     axios
      .get("/api/customers", {
        params: {
          firstName: this.state.firstName
        }
      })
      .then(res => {
        console.log(res);
        this.setState({ res: this.state.customers });
      });
     };

     componentDidMount() {}

     render() {


     //if (!this.state.customers.length) return "Data not available yet";
      return (
       <div>
        <h2>Customers</h2>
        <div className="card card-body mb-4 p-4">
          <div className="h1 display-4 text-center">
            <h1 className="i fas">Search for a customer</h1>
            <p className="lead text-center">Get the Customer's Name Here</p>
            <form onSubmit={this.getName}>
              <div className="form-group">
                <input
                  type="text"
                  className="form-control form-control-lg"
                  placeholder="customer name ..."
                  name="firstName"
                  value={this.state.firstName}
                  onChange={this.onChange}
                />
              </div>
              <button
                className="btn btn-primary btn-lg-block mb-5"
                type="submit"
              >
                Get Customer
              </button>
            </form>
          </div>
        </div>

这是我循环遍历数据的地方:

        {this.state.customers.map(item => (
          <li key={item.id}>{item.firstName}</li>
        ))}
      </div>
    );
  }
}

这是我呼叫的特快路线:

app.get("/api/customers", (req, res) => {
  let { firstName } = req.query;
  const customers = [
    { id: 1, firstName: "John" },
    { id: 2, firstName: "Brad" },
    { id: 3, firstName: "Mary" }
  ];
  console.log("the customer's name is " + firstName);
  var str = customers.filter(x => x.firstName == firstName);
  res.json(str);

});

所以我想要的是在输入栏下方的元素中显示数据。

【问题讨论】:

    标签: reactjs express get axios


    【解决方案1】:

    试试看:

    this.setState({ customers : res });
    

    而不是:

    this.setState({ res: this.state.customers });
    

    另外,尝试使用 React Hooks 来重构您的代码。

    【讨论】:

    • 感谢大卫的提示。您的解决方案对我不起作用,但它为我指明了正确的方向。我将这一行改为: this.setState({ customers: res.data });它有效。不过我接受你的回答。对于 React 钩子,我还没有。
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多