0
我正在玩redux-thunk並試圖從隨機API中獲取數據,並且有一個問題: 正如您在我的控制檯屏幕截圖中所看到的,我當控制檯記錄用戶的數據時,獲得一個空陣列2次,這真的很糟糕。好像我做錯了什麼。我該如何去做這個請求,所以它不會記錄一個空數組?請求componentWillMount中的數據會得到相同的結果。使用AJAX請求設置狀態,使用REDX-thunk
商店:
const initialState = {
users: {
isFetching: false,
receivedAt: null,
error: null,
userList: []
}
}
const store = createStore(
rootReducer,
initialState,
applyMiddleware(
thunk,
createLogger()
)
)
減速:
function users(state = {},action) {
switch(action.type) {
case 'REQUEST_USERS':
return {
...state,
isFetching:true
}
case 'RECEIVE_USERS':
return {
...state,
isFetching: false,
receivedAt: action.receivedAt,
userList: action.users
}
case 'REQUEST_ERROR':
return {
...state,
error: action.err
}
default: return state
}
}
const rootReducer = combineReducers({
users
})
ActionCreators:
export function requestUsers() {
return {
type:'REQUEST_USERS'
}
}
function receiveUsers(users) {
return {
type:'RECEIVE_USERS',
users: users.results,
receivedAt: Date.now()
}
}
function requestError(err) {
return {
type:'REQUEST_ERROR',
err
}
}
export function loadUsers() {
return dispatch => {
dispatch(requestUsers())
return fetch('https://randomuser.me/api/?results=50')
.then(response => response.json())
.then(users => dispatch(receiveUsers(users)))
.catch(err => dispatch(requestError(err)))
}
}
容器的代碼:
function mapStateToProps (state) {
return {
users: state.users
}
}
function mapDispatchToProps (dispatch) {
return bindActionCreators(actionCreators, dispatch)
}
const App = connect(mapStateToProps, mapDispatchToProps)(Main)
我的組件代碼:
componentDidMount() {
this.props.loadUsers()
}
render() {
const {userList} = this.props.users
console.log(userList)
const users = userList.map((user,i) => <li key={i}>{user.name.first + ' ' + user.name.last}</li>)
return (
<div>
<ul>
{users}
</ul>
</div>
)
}
}
如果沒有看到更多的代碼(減速器,你如何連接到商店等等),真的很難說: 和請,縮進代碼,這讓我很頭疼 – thedude
已添加到帖子。我連接到商店,使用連接(mapStatetoProps,mapDispatchToProps)(主) – Umbrella
Sry,我不知道如何在這裏縮進代碼,它粘貼時會失去所有縮進。 – Umbrella