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

React/Redux:mapStateToProps()为什么会使数组的存储状态消失?,redux,react-redux,redux-thunk,Redux,React Redux,Redux Thunk,在我的商店中,我有一个这样形状的状态:{posts:[{…},{…}]},但是当我在Home.js中使用mapStateToProps()时,状态返回{posts:[]},带有一个空数组(在商店的状态中曾经有一个数组) 我是否错误地使用了MapStateTops(),或者问题是否源于Redux周期的其他部分 我正在使用的API获取,临时位于actions.js中 // api const API = "http://localhost:3001" let token = localStora

在我的商店中,我有一个这样形状的状态:
{posts:[{…},{…}]}
,但是当我在Home.js中使用
mapStateToProps()
时,状态返回
{posts:[]}
,带有一个空数组(在商店的状态中曾经有一个数组)

我是否错误地使用了
MapStateTops()
,或者问题是否源于Redux周期的其他部分

我正在使用的API获取,临时位于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 })
);

使用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))
                )
    }
}

减速器:

// rootReducer.js

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

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

临时包含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();
在Home.js组件中,
console.log('Props',this.Props)
返回{posts:[]},其中我期望{posts:[{…},{…}]}

***编辑: 在分派前的操作和减速器中添加
console.log()
后,以下是控制台输出:

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;
    }
}
然后在MapStateTops函数中:

function mapStateToProps(state) {
    return {
        posts: state.posts
    }
}

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;
    }
}
然后在MapStateTops函数中:

function mapStateToProps(state) {
    return {
        posts: state.posts
    }
}

一切似乎都很好。您确定在获取中有结果吗?你能在分派之前在你的操作中放置一个
控制台。log
,在reducer中放置一个吗?好主意,我添加了它们,并删除了上面控制台输出的链接-在action、reducer和store中,提取返回似乎是正确的,但在组件中它消失了一切似乎都很好。您确定在获取中有结果吗?您能在分派之前在您的操作中放置一个
控制台。log
,在reducer中放置一个吗?好主意,我添加了它们,并删除了上面控制台输出的链接-似乎在操作、reducer和store中获取返回是正确的,但在组件中它消失了