ReactJS - 在ajax函数呈现数据后执行javascript代码

问题描述 投票:1回答:2

我应该在哪里放置JavaScript代码,以便在渲染完成后我可以调用插件。

<html>

<head>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/es6-promise/3.2.2/es6-promise.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/axios/0.13.1/axios.min.js'></script>
  <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>

<body>


  <div id="root"></div>


  <script type="text/babel">

    const REST_API = 'users.json';

// The root component
const App = props => (
  <div className="app">
      <UserListContainer />
   </div>
);

// Container
class UserListContainer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      users: [{
        name: 'Loading data...'
      }]
    };
  }

  loadData() {
    axios.get(REST_API).then((response) => {
      //console.log(response.data);
      this.setState({
        users: response.data
      })
    });
  }

  // Life cycles hooks
  // facebook.github.io/react/docs/component-specs.html
  componentWillMount() {};
  componentDidMount() {
    // Data is loaded async, therefore will be inserted after first DOM rendering
    this.loadData();
  };
  componentWillReceiveProps(nextProps) {};
  shouldComponentUpdate(nextProps, nextState) {
    return true;
  };
  componentWillUpdate(nextProps, nextState) {};
  componentDidUpdate(prevProps, prevState) {};
  componentWillUnmount() {};

  render() {
    return (<UserList users={this.state.users} />);
  };
}

// Presentation
const UserItem = (user, index) => (
  <li key={index}>
          <div className="header"> 
            <div className="name"> {user.name}</div>

            <div className="index">{(index+1)}</div>
          </div>

            <div className="date">
            <i className="fa fa-date" aria-hidden="true"></i>
            <span>{user.date}</span>
          </div>



          <div className="contact">
            <i className="fa fa-phone" aria-hidden="true"></i>
            <span>{user.phone}</span>
          </div>
      </li>
);
const UserList = props => (
  <div className="user-list">
    <h1>React ES6 Ajax, Container and Presentation - example</h1>
    <ul>
        {props.users.map(UserItem)}
     </ul>
   </div>
);

// Render
ReactDOM.render(
  <App />, document.getElementById('root')
);

    </script>



</body>

</html>

我把它添加到了

  componentDidUpdate(prevProps, prevState) {
    alert();
  };

然后,在第一个元素之后,警报功能正在工作,

这些是我的实际文件 - https://drive.google.com/drive/folders/1G7UOaCFS_521hfZc4-jNeLGiKR4XaQjP?usp=sharing

enter image description here

enter image description here

javascript ajax reactjs
2个回答
1
投票

如果我正确理解您的要求,那么componentDidUpdate()钩子将是用于访问DOM(并调用您的插件)的正确钩子。这将在您的组件渲染后调用。

作为state in the official docscomponentDidUpdate()

将此作为在更新组件时对DOM进行操作的机会。只要您将当前道具与之前的道具进行比较(例如,如果道具未更改,则可能不需要网络请求),这也是进行网络请求的好地方。

需要注意的一件重要事情是componentDidUpdate()挂钩不会为第一次渲染而触发。

更新

要解决这个“第一次渲染”问题,您可以使用可以传递给setState(state, callback)的可选回调。渲染组件后会触发此callback(状态更改后)。

在你的情况下,你可以做这样的事情:

loadData() {
    axios.get(REST_API).then((response) => {
      //console.log(response.data);
      this.setState({ users: response.data }, () => {

           // When this callback is invoked, the component has been 
           // rendered and the DOM can be safely accessed
      })
    });
  }

1
投票

componentDidMount是获取数据的正确位置,你正确地做到了。如果您需要接收道具或状态并相应更新,则使用componentDidUpdate钩子。如果您的子组件要通过接收数据从父组件更新它们,则这是必需的。但在查看您的代码后,我没有注意到您需要父组件。所以,你不需要componentDidUpdate钩。您只需要执行以下操作。

保持状态如下:

this.state = {
  users: [],
  loading: true,
  loadingText: 'Loading data...'
};

然后,在您将数据集加载到false后获取:

loadData() {
    axios.get(REST_API).then((response) => {
      //console.log(response.data);
      this.setState({
        users: response.data,
        loading: false
      })
    });
  }

现在,当你渲染它们时:

const UserList = props => (
  <div className="user-list">
    <h1>React ES6 Ajax, Container and Presentation - example</h1>
    <ul>
        {!props.loading && props.users && props.users.map(UserItem)}
     </ul>
   </div>
);

注意:您还必须通过加载状态。

© www.soinside.com 2019 - 2024. All rights reserved.