Ty *_*opp 0 redux redux-thunk react-redux
在我的商店中,我有一个具有以下形状的状态:{posts: [{...},{...}]},但是当我mapStateToProps()在 Home.js 中使用时,状态返回{posts: []},带有一个空数组(商店状态中曾经有一个数组)。
我是否使用mapStateToProps()不正确或者问题是否源于 Redux 周期的其他部分?
我正在使用的 API fetch,暂时位于 actions.js 中
// api
const API = "http://localhost:3001"
let token = localStorage.token
if (!token) {
token = localStorage.token = Math.random().toString(36).substr(-8)
}
const headers = {
'Accept': 'application/json',
'Authorization': token
}
// gets all posts
const getAllPosts = token => (
fetch(`${API}/posts`, { method: 'GET', headers })
);
Run Code Online (Sandbox Code Playgroud)
动作和动作创建者,使用 thunk 中间件:
// actions.js
export const REQUEST_POSTS = 'REQUEST_POSTS';
function requestPosts (posts) {
return {
type: REQUEST_POSTS,
posts
}
}
export const RECEIVE_POSTS = 'RECEIVE_POSTS';
function receivePosts (posts) {
return {
type: RECEIVE_POSTS,
posts,
receivedAt: Date.now()
}
}
// thunk middleware action creator, intervenes in the above function
export function fetchPosts (posts) {
return function (dispatch) {
dispatch(requestPosts(posts))
return getAllPosts()
.then(
res => res.json(),
error => console.log('An error occured.', error)
)
.then(posts =>
dispatch(receivePosts(posts))
)
}
}
Run Code Online (Sandbox Code Playgroud)
减速器:
// rootReducer.js
function posts (state = [], action) {
const { posts } = action
switch(action.type) {
case RECEIVE_POSTS :
return posts;
default :
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
临时包含 Redux 存储的根组件:
// index.js (contains store)
const store = createStore(
rootReducer,
composeEnhancers(
applyMiddleware(
logger, // logs actions
thunk // lets us dispatch() functions
)
)
)
store
.dispatch(fetchPosts())
.then(() => console.log('On store dispatch: ', store.getState())) // returns expected
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<Quoted />
</Provider>
</BrowserRouter>, document.getElementById('root'));
registerServiceWorker();
Run Code Online (Sandbox Code Playgroud)
主要成分:
// Home.js
function mapStateToProps(state) {
return {
posts: state
}
}
export default connect(mapStateToProps)(Home)
Run Code Online (Sandbox Code Playgroud)
在 Home.js 组件中,console.log('Props', this.props)返回 {posts: []},我期望的是 {posts: [{...},{...}]}。
*** 编辑:在console.log()调度之前的操作和减速器中添加 a 之后,这里是控制台输出:
控制台输出链接(代表还不够高,无法嵌入)
redux 存储应该是一个对象,但似乎它在根减速器中被初始化为数组。您可以尝试以下操作:
const initialState = {
posts: []
}
function posts (state = initialState, action) {
switch(action.type) {
case RECEIVE_POSTS :
return Object.assign({}, state, {posts: action.posts})
default :
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的mapStateToProps函数中:
function mapStateToProps(state) {
return {
posts: state.posts
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2113 次 |
| 最近记录: |