如何实现“显示更多”按钮?

时间:2019-07-29 09:56:52

标签: javascript reactjs

我要实现按钮行为显示更多
当我单击按钮时,必须加载新对象而无需重新启动。

我执行const [data, setData] = useState(users);来初始化前10个用户。
当我按下按钮时,将其添加到此数组data中,然后添加以下10个用户

var users = response.data;
for (var i=0; i < users.length; i++) {
  data.push(users[i]);
}
setData(data);

但是浏览器中没有任何内容。

如何纠正?

const Cards = ({users, bottomUrl }) => {
  const [data, setData] = useState(users);

  const handleSubmit = e => {
    e.preventDefault();

    const page = bottomUrl.slice(-1);
    const axios = require('axios');
    const url = '/users';

    axios.get(url, {
      params: { page: page }
    }, {headers: {'Content-Type': 'application/json'}})
    .then(function (response) {
      var users = response.data;
      for (var i=0; i < users.length; i++) {
        data.push(users[i]);
      }
      setData(data);
    })
    .catch(function (error) {
      console.log(error);
    })
    .then(function () {
      // always executed
    });
  };

  return (
    <div>
      <div className="users-list">
        {data.map((element, elIndex) => (
          <UserCard
            key={elIndex}
            lastName={element.lastName}
            firstName={element.firstName}
            description={element.description}
          />
        ))}
      </div>

      <div className="users-page-button-container">
        <a className="button" onClick={handleSubmit} href={bottomUrl}>Show more</a>
      </div>
    </div>
  )

};

2 个答案:

答案 0 :(得分:0)

您正在推动状态对象data。您必须使用中间变量并将其传递给setData

答案 1 :(得分:0)

您正在直接操纵状态,这是错误的。请如下更新handleSubmit方法。

 const handleSubmit = e => {
    e.preventDefault();

    const page = bottomUrl.slice(-1);
    const axios = require('axios');
    const url = '/users';

    axios.get(url, {
      params: { page: page }
    }, {headers: {'Content-Type': 'application/json'}})
    .then(function (response) {
      users = response.data;
      setData([...data, ...users]); // You need to save the previous data along with the new data and pass it together to setData function. So here data = previous data + new users data
    })
    .catch(function (error) {
      console.log(error);
    })
    .then(function () {
      // always executed
    });
  };