我在运行我的应用程序时遇到了一些麻烦。我对React和Redux很新,所以请耐心等待。
现在我可以调用this.props.fetchData('usernamehere')
来获取有关用户的一些数据,当它成功更新this.props.profile
时,我会用它来更新React组件。这个问题是处理错误。
我已尝试通过添加FETCH_DATA_ERROR
缩减器来处理此问题,但我遇到的问题是,当它404仍然用this.props.profile
取代this.props.error
时空对象,而不仅仅是更新this.props.error
。理想情况下,我希望保留当前配置文件,直到它成功找到新配置文件,然后通过更新import axios from 'axios';
import { FETCH_DATA, FETCH_DATA_ERROR } from './types';
export const ROOT_URL = 'https://api.github.com/users'
export function fetchData(user) {
const request = axios.get(`${ROOT_URL}/${user}`)
.catch(function (error) {
return {
type: FETCH_DATA_ERROR,
payload: error
}
});
return {
type: FETCH_DATA,
payload: request
}
}
向用户显示他们输入的用户名的错误。
现在我有以下动作创建者设置:
import { FETCH_DATA, FETCH_DATA_ERROR } from '../actions/types';
const INITIAL_STATE = { profile: null, error: null }
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_DATA:
return { ...state, profile: action.payload.data };
case FETCH_DATA_ERROR:
return { ...state, error: action.payload };
default:
return state;
}
}
还原剂:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
如果有人有任何建议,我们将不胜感激。我觉得自己正走在正确的道路上,但似乎无法弄清楚我哪里出错了。
答案 0 :(得分:1)
到目前为止,您有一个动作表示请求的开始(FETCH_DATA
),另一个表示请求失败(FETCH_DATA_ERROR
)。通常情况下,这是使用第三个建模,表明请求产生了积极响应(可能是FETCH_DATA_SUCCESS
)。
您需要使用类似https://github.com/gaearon/redux-thunk的内容重写您的操作创建者,以便它首先仅调度FETCH_DATA
,然后在axios.get
的then / catch-handler中调度成功或失败的行动:
import { FETCH_DATA, FETCH_DATA_SUCCESS, FETCH_DATA_ERROR } from '../actions/types';
// ASYNC ACTION CREATOR
export const fetchData = user => (dispatch) => {
dispatch({
type: FETCH_DATA
});
return axios.get(`${ROOT_URL}/${user}`)
.then(response => dispatch({
type: FETCH_DATA_SUCCESS,
payload: response
}))
.catch(error => dispatch({
type: FETCH_DATA_ERROR,
payload: error
}));
};
// REDUCER
const INITIAL_STATE = {
profile: null,
error: null
};
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
// Start of request - discard old data and reset old errors.
case FETCH_DATA:
return {
// It's important to set all of these to properly model the request lifecycle
// and avoid race conditions etc.
profile: null,
error: null
};
// End of request - save profile and signal that there was no error.
case FETCH_DATA_SUCCESS:
return {
profile: action.payload.data,
error: null
};
// End of request - discard old profile and save error, to display it to the user for example.
case FETCH_DATA_ERROR:
return {
profile: null,
error: action.payload
};
default:
return state;
}
}