如何使JS请求做出反应?

时间:2019-07-29 06:38:21

标签: javascript ruby-on-rails reactjs axios

单击按钮时,我有一个“显示更多” ,而无需重新启动,我想加载新对象

const UsersPageButton = ({ bottomUrl }) => {
  const userClick = e => {
    e.preventDefault();
    const page = bottomUrl.slice(-1);
    const axios = require('axios');
    const url = '/users'
    const data = { 'page': page };

    const options = {
      method: 'get',
      headers: { "Content-Type": "application/json" },
      data: data,
      url,
    }

    axios(options);
  };
  return (
    <a className="button" onClick={userClick} href={bottomUrl}>Show more</a>
  )

};

根据此请求,我得到了另一包对象,并已经使用 index.js.erb

进行显示
$(".users-list").html("<%= j render 'users/users', users: @users %>")

但是对控制器的请求是 HTML 格式的,因此不会呈现 index.js.erb

如何发送脚本请求(JS请求)以呈现 index.js.erb

1 个答案:

答案 0 :(得分:0)

您应该将axios响应传递给组件,该响应将呈现所有已获取的用户。

更好的解决方案是将axios请求与按钮分开,仅保留onClick处理程序道具。例如:

  const userClick = e => {
    e.preventDefault();
    const page = bottomUrl.slice(-1);
    const axios = require('axios');
    const url = '/users'
    const data = { 'page': page };

    const options = {
      method: 'get',
      headers: { "Content-Type": "application/json" },
      data: data,
      url,
    }
    // Notice the 
    axios(options).then(response => this.setState({data: response.data});
  };

  return (
  <div>
    <UsersList data={data} />
    <UsersPageButton onClick={userClick} />
  </div>
  );