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

时间:2018-09-04 03:59:49

标签: javascript ajax reactjs

我应该在哪里放置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/babel-standalone@6.15.0/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

2 个答案:

答案 0 :(得分:1)

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

componentDidUpdate()的{​​{3}}一样:

  

使用此机会在组件更新后在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 :(得分: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>
);

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