【问题标题】:Understanding how axios works in react native了解 axios 在 react native 中的工作原理
【发布时间】:2019-12-27 09:51:28
【问题描述】:

所以我今天遇到了一个我不太明白的问题。 这里是: 所以基本上我有一个带有 mongoDB 的节点 js 服务器作为后端,当我调用我的第一个组件时,我执行以下操作: 在构造函数中,我调用了一个函数,该函数将返回一个数组,除了登录的用户之外,所有用户都将返回一个数组

fetchUsers = () => {
        axios.get(userAPI) //Array from all users in DB
        .then((res)=>{
          for(var k = 0; k <(res.data.length); k++){
            console.log(this.state.idUser)
            if(this.state.idUser==res.data[k]._id){
                console.log("forget same user")
            }
            else
            {
              realUsers.push(res.data[k])
            }
          }
          console.log(realUsers)
        })

我不明白的是在这个函数中 this.state.idUser 等于登录用户的 id,并且它不为空,但是当我在构造函数中调用第二个 axios 函数时,该函数接受 URL 链接+this.state.idUser 这次idUser的状态为null。

historyUsers = () =>{
       axios({
         method:'GET',
         url : urlArrayHistory+this.state.idUser
       })
       .then((response)=>{
         console.log("response de historyVote",response)
         const realUsersId = []
         for(let p=0; p<realUsers.length;p++){
           realUsersId.push(realUsers[p]._id)
         }
         for(let k = 0;k<response.data[0].historyVote.length;k++){
           if(realUsersId.includes(response.data[0].historyVote[k])){
             console.log("it's in",realUsers)
             realUsers.pop(k)
             console.log(realUsers)
           }
           else{
             console.log("ain't in")
           }
         }
       })
     }

最后我想要的是它比较我的应用程序上所有用户的 realUsers 数组 以及来自 historyVote 的数组,它们是当前用户(已登录的用户)已经遇到的所有用户。

感谢您的帮助 :) 如果您需要更多代码或其他内容,请告诉我。

编辑:这是我的组件的完整代码


  const userAPI = 'http://localhost:5050/api/new/users'
  const urlHistory = 'http://localhost:5050/api/vote/historyvote/'
  const urlArrayHistory = 'http://localhost:5050/api/vote/array/'
  const realUsers = []


const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;


export default class HomeScreen extends React.Component{
    constructor(props){
        super(props)
        this.position = new Animated.ValueXY()
        this.state={
          currentIndex : 0,
          idUser : null,
          nameUser : null,
          scoreUser : null,
          currentAdverseId :"",
          currentToken : this.props.screenProps.jwt,
          readyRender : 0,
          voteHistory : [],
        }
this.infoUserAdverse = {
          name :"",
          age : "",
          Score:"",
          idAdverse :""
        }
}
retrieveId = () =>{ //Get back the Id of current logged in user from the token
      const header = {
        'authorization':'Bearer '+this.props.screenProps.jwt
      }
      console.log(header)
      axios.get('http://localhost:5050/api/posts',{
        headers : header
      })
      .then((response) =>{
        console.log(response)
        this.setState({idUser: response.data._id})
        console.log(this.state.idUser)
    })
    .catch((error)=>{
      console.log(error)
    })
  }
      historyUsers = () =>{
        axios({
          method:'GET',
          url : urlArrayHistory+this.state.idUser
        })
        .then((response)=>{
          console.log("response de historyVote",response)
          const realUsersId = []
          for(let p=0; p<realUsers.length;p++){
            realUsersId.push(realUsers[p]._id)
          }
          for(let k = 0;k<response.data[0].historyVote.length;k++){
            if(realUsersId.includes(response.data[0].historyVote[k])){
              console.log("it's in",realUsers)
              realUsers.pop(k)
              console.log(realUsers)
            }
            else{
              console.log("ain't in")
            }
          }
        })
      }
      fetchUsers = () => {
        axios.get(userAPI) //Array from all users in DB
        .then((res)=>{
          for(var k = 0; k <(res.data.length); k++){
            if(this.state.idUser==res.data[k]._id){
                console.log("forget same user")
            }
            else
            {
              realUsers.push(res.data[k])
            }
          }
          console.log(realUsers)
        })
      }

      apiFetchId = () => 
      {
        const newHeader = {
        'authorization':'Bearer '+this.state.currentToken
      }
        axios.get('http://localhost:5050/api/new/'+this.state.idUser,{
        headers: newHeader
      })
      .then((res)=>{
        console.log(res)
        this.setState({
          nameUser:res.data.name,
          scoreUser:res.data.Score,
          voteHistory:res.data.historyVote
        })
      })
      }
componentDidMount(){
        this.fetchUsers()
        this.apiFetchId()
        //this.historyUsers()
        //this.renderUsers()
    }
renderUsers = () => {
        return realUsers.map((item, i) => {
          if(i< this.state.currentIndex){
            return null
          }
          else if (i == this.state.currentIndex){
            console.log("render users cas 2")
            this.infoUserAdverse=realUsers[i]
            return (
              <Animated.View
                {...this.PanResponder.panHandlers}
                key={item._id} style={[this.rotateAndTranslate , { height: SCREEN_HEIGHT - 220, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
                  <Animated.View style={{ opacity: this.likeOpacity, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
                    <Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>++</Text>
                  </Animated.View> 
                  <Animated.View style={{ opacity: this.dislikeOpacity, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
                    <Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>--</Text>
                  </Animated.View>

                <Image
                  style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
                  source={{uri:"http://localhost:5050/"+item.userImage}} />
              </Animated.View>

            )
          }
          else {
            console.log("render users cas 3")
            return (
              <Animated.View
                key={item._id} style={[{
                  opacity: this.nextCardOpacity,
                  transform: [{scale: this.nextCardScale}], 
                  height: SCREEN_HEIGHT - 220, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
                <Image
                  style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
                  source={item.uri} />

              </Animated.View>
            )
          }
        }).reverse()
      }


      addHisotryUser =  () => {
        let urlHistory2 = urlHistory+this.state.idUser
        console.log(urlHistory2)
        axios({ 
          method: 'PATCH',
          url: urlHistory2,
          //headers: {authorization: 'Bearer '+this.state.currentToken},
          data: { 
            userId: this.infoUserAdverse._id,
          } 
        })
        .then((res)=>{
          console.log(res)
        })
        .catch((err)=>{
          console.log(err)
        })
      }

【问题讨论】:

  • 首先,为什么要在构造函数中加载应用数据?应该在componentDidMount()useEffect() 钩子中加载。
  • 添加完整的组件来源
  • 你好,我真的不知道我为什么这样做,我只是想让用户用户在它显示在屏幕上之前进行渲染,但我只是移入了 ComponentDidMount() 并且它正在工作。
  • 我可以添加完整的源代码,是的,但我希望你能够理解所有内容,我是计算机科学的初学者,我所写的内容对于我相信的每个人来说可能并不容易理解。

标签: reactjs react-native networking axios


【解决方案1】:

我认为这是由于在您开始调用 Axios 方法后设置了状态。

在第一个 Axios 查询 fetchUsers 中,首先联系服务器,只有在收到响应后,代码才会查看 state.idUser。在第二个查询中,historyUsersstate.idUser 需要在联系服务器之前立即构造一个 URL。 fetchUsers 的延迟足以同时设置状态。

确保在您的构造函数中,在您调用fetchUsershistoryUsers 之前,您实际上已经设置了this.state = { idUser: xxx }

【讨论】:

  • 好的,谢谢我完全理解,我正在从他登录时获得的令牌中检索ID用户,所以我需要做的是在我的构造函数中调用该函数以取回userId令牌对吗?
  • 只要确保在调用任何 Axios 方法之前确实设置了 state.idUser
  • 我觉得我的 componentDidMount() 被调用了,而我的 constructor() 也被调用了你知道为什么吗?
  • 您的组件已构建,然后安装。这两件事都发生在组件生命周期的开始。最好在构造函数中设置你的状态,然后在componentDidMount中做你的Axios请求。
  • 好的,但我认为 componentDidMount 会在组件完成渲染后运行。所以我在构造函数中所做的是获取用户的 id 来设置状态。但是,如果我尝试获取数据以显示在我的屏幕上,但我将函数放在 componentDidMount() 中,它将不会使用状态 id null 而不是从构造函数更新的那个。
猜你喜欢
  • 2016-02-20
  • 2012-12-11
  • 2011-02-18
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多