首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React/Redux:为什么mapStateToProps()使数组的存储状态消失?

React/Redux:为什么mapStateToProps()使数组的存储状态消失?
EN

Stack Overflow用户
提问于 2017-11-05 19:58:47
回答 1查看 2.1K关注 0票数 0

在我的商店中,我有一个具有以下形状的状态:{posts: [{...},{...}]},但是当我在Home.js中使用mapStateToProps()时,状态返回{posts: []},其中包含一个空数组(在存储的状态中曾经有一个数组)。

我是不正确地使用mapStateToProps(),还是这个问题来自于Redux循环的其他部分?

我正在使用的API,暂时位于actions.js中

代码语言:javascript
运行
复制
// 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 })
);

动作和动作创建者,使用thunk中间件:

代码语言:javascript
运行
复制
// 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))
                )
    }
}

减速机:

代码语言:javascript
运行
复制
// rootReducer.js

function posts (state = [], action) {
    const { posts } = action

    switch(action.type) {
        case RECEIVE_POSTS :
            return posts;
        default : 
            return state;
    }
}

临时包含Redux存储的根组件:

代码语言:javascript
运行
复制
// 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();

主要构成部分:

代码语言:javascript
运行
复制
// Home.js
function mapStateToProps(state) {
    return {
        posts: state
    }
}


export default connect(mapStateToProps)(Home)

在Home.js组件中,console.log('Props', this.props)返回{posts:[]},其中我期望{posts:{.},{.}}。

*编辑:在调度之前的操作和还原器中添加console.log()之后,下面是控制台输出:控制台输出链接(还没有足够高的rep嵌入)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-06 01:51:07

redux存储应该是一个对象,但是它似乎被初始化为根还原器中的一个数组。您可以尝试以下方法:

代码语言:javascript
运行
复制
const initialState = {
    posts: []
}

function posts (state = initialState, action) {

    switch(action.type) {
        case RECEIVE_POSTS :
            return Object.assign({}, state, {posts: action.posts})
        default : 
            return state;
    }
}

然后在您的mapStateToProps函数中:

代码语言:javascript
运行
复制
function mapStateToProps(state) {
    return {
        posts: state.posts
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47126005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档