简体   繁体   English

我应该在哪里获取异步数据?

[英]Where I should fetch async data?

I am fetching data using axios and then map state to props with redux but I have a problem.我正在使用axios然后 map state 获取数据到带有 Z7490FE17CAEC3703F2880ZD26 的道具的问题。 If I dispatch the action in componentDidUpdate() the action execute indefinitely and if I used the constructor(props) I get undefined value for props so where I should fetch the data?如果我在componentDidUpdate()中调度动作,动作会无限期地执行,如果我使用constructor(props)我会得到道具的undefined值,那么我应该在哪里获取数据?

import React, { Component } from 'react'
import {connect} from 'react-redux'
import { getUserPosts } from '../../actions'

class UserPosts extends Component {

    //UNSAFE_componentWillMount() {

    //}
    constructor(props) {
        super(props);
        console.log(props);
    }


    componentDidUpdate() {
        //this.props.dispatch(getUserPosts(this.props.user_reducer.login?.user._id));
    }

    showUserPosts = (user) => (

        Array.isArray(user.userPosts) ?
          user.userPosts.map((item, i) => (
                <tr key={i}>
                <td>{i}</td>
                <td>author</td>
                <td>date</td>
                </tr>    

          ))
        : null    

    )

    render() {
        let user = this.props.user_reducer;
        //console.log(user.userPosts);
        return (
            <div>
               <div className="user_posts">
                   <h4>Your reviews:</h4>
                   <table>
                       <thead>
                           <tr>
                               <th>Name</th>
                               <th>Author</th>
                               <th>Date</th>
                           </tr>
                       </thead>
                       <tbody>
                           {this.showUserPosts(user)}
                       </tbody>
                   </table>
               </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    //console.log(state);
    return {
        user_reducer: state.user_reducer
    }
}

export default connect(mapStateToProps)(UserPosts)

action:行动:

export function getUserPosts(userId) {
    const req = axios.get(`/api/user_posts?user=${userId}`)
                .then(res => res.data);

    return {
        type: 'GET_USER_POSTS',
        payload: req
    }
}

componentDidMount() is the best placement for the call to fetch. componentDidMount()是调用 fetch 的最佳位置。

Here is an example implementation of the axios fetch from componentDidMount():这是从 componentDidMount() 获取 axios 的示例实现:

import React from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

class UserPosts  extends React.Component {
constructor(props) {
  super(props)

  // Initiate state with an empty array of user posts
  this.state = { userPosts: [] }
}



componentDidMount() {
  axios.get('http://api-url-here')
  .then((response) => {

    // Set the userPosts when data is received.
    // render method will show user posts when state changes

    this.setState({userPosts: response.data})

  })

}

showUserPosts = (user) => (

  Array.isArray(user.userPosts) ?
    user.userPosts.map((item, i) => (
          <tr key={i}>
          <td>{i}</td>
          <td>author</td>
          <td>date</td>
          </tr>    

    ))
  : null    

)

render() {
  let user = this.state;
  //console.log(user.userPosts);
  return (
      <div>
         <div className="user_posts">
             <h4>Your reviews:</h4>
             <table>
                 <thead>
                     <tr>
                         <th>Name</th>
                         <th>Author</th>
                         <th>Date</th>
                     </tr>
                 </thead>
                 <tbody>
                     {this.showUserPosts(user)}
                 </tbody>
             </table>
         </div>
      </div>
  )
}
}




ReactDOM.render(<UserPosts  />, document.getElementById('root'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM