2017-01-22 72 views
0

我对React/React Native/Redux很新颖,所以我觉得我做错了什么。React Native Redux:API调用后不会更新道具

我想表现出微调而一个API调用的问题,一旦这个API调用失败的错误消息。道具没有更新,因此部件不显示所期望的消息或喷丝

的代码(仅相关的块),

组件

class Home extends Component { 

    componentWillMount() { 
     this.props.tokenGet(); 
    } 

    renderSpinner() { 
     if (this.props.loading) { 
      return (
       <Spinner size="large" /> 
      ); 
     } 
     return null; 
    } 

    renderMessage() { 
     if (this.props.message) { 
      return (
       <Text style={{flex: 1, background: red, color: black}}> 
        { this.props.message } 
       </Text> 
      ) 
     } 
     return null; 
    } 

    render() { 
     return (
      { this.renderSpinner() } 
      { this.renderMessage() } 
     ) 
    } 
} 


const mapStateToProps = (state) => { 
    const { auth } = state; 
    const { 
     loading, 
     token, 
     message 
    } = auth || { 
     loading: false, 
     token: null, 
     message: null 
    }; 
    return { 
     loading, 
     token, 
     message 
    } 
}; 


export default connect(mapStateToProps, { tokenGet })(Home); 

动作创作者

export const tokenGet =() => { 
    return (dispatch) => { 
     dispatch({ type: 'TOKEN_GET_START'}); 

     // Perform the actual API call 
     let requestToken = fetch(apiBaseUrl + "/tokens", { 
      method: "POST", 
      headers: { 
        'Accept': 'application/json', 
        'Content-Type': 'application/json' 
      }, 
      body: JSON.stringify(.....) 
     }); 
     Promise 
      .race([timeout, requestToken]) 
      .then((response) => response.json()) 
      .then((responseJson) => { 
        ... not relevant ... 
      }) 
      .catch((error) => { 
       dispatch({ type: 'TOKEN_GET_FAIL', payload: error}); 
      }); 

超时功能,这被称为当服务器无法响应

let timeout = new Promise((resolve, reject) => { 
    setTimeout(reject, 2000, 'Request timed out. Please check your internet connection.'); 
}); 

减速器

import { 
    TOKEN_GET_START, 
    TOKEN_GET_SUCCESS, 
    TOKEN_GET_FAIL 
} from '../actions/types'; 

const INITIAL_STATE = { 
    loading: false, 
    token: null, 
    message: null 
}; 

export default (state = INITIAL_STATE, action) => { 
    switch (action.type) { 
     case TOKEN_GET_START: 
      return { ...state, loading: true }; 
     case TOKEN_GET_SUCCESS: 
      return { ...state, loading: false, token: action.payload }; 
     case TOKEN_GET_FAIL: 
      return { ...state, loading: false, message: action.payload }; 
     default: 
      return state; 
    } 
}; 

合并减速

import { combineReducers } from 'redux'; 
import AuthReducer from './AuthReducer'; 

export default combineReducers({ 
    auth: AuthReducer 
}); 

的实际行为道具不会改变并且没有消息或微调器可见。对于某些控制台日志,我知道由于超时而导致API调用结束。我不确定状态是否正确更新。我不知道在哪一点我可以控制台登录。

回答

0

原来是因为引号的'TOKEN_GET_FAIL'

这是一个字符串,而不是const我所需要的。所以我改为TOKEN_GET_FAIL,它的工作原理。

相关问题