首页 文章

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

提问于
浏览
0

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

我是否错误地使用 mapStateToProps() 或问题是否源于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
function mapStateToProps(state) {
    return {
        posts: state
    }
}


export default connect(mapStateToProps)(Home)

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

***编辑:在发送前和减速器中的操作中添加 console.log() 后,这是控制台输出:Console output link (not high enough rep to embed yet)

1 回答

  • 2

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

    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函数中:

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

相关问题