反应:遍历数组响应不起作用

时间:2019-10-15 21:29:26

标签: reactjs express get axios

我向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>
    );
  }
}

这是我正在拨打的Express路线:

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);

});

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

1 个答案:

答案 0 :(得分:0)

尝试:

this.setState({ customers : res });

而不是:

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

此外,尝试使用React Hooks来重构代码。