React Redux -> Map 不是函数?

所以我正在学习如何使用 redux 和 redux persist,目前我遇到了一个问题。每当我尝试映射我商店的内容时,它都会抛出一条错误消息TypeError: tasks.map is not a function,我真的不知道为什么会出现这个问题。我用谷歌搜索并尝试调试它,也尝试重写代码几次,但都无济于事。这是我的全部代码:rootReducer.js


import React from 'react'


let nextToDo = 0;

const task=[

    {

    }

]

const reducer =(state=task, action)=>

{

    switch(action.type)

    {

        case 'add':

            return[

                ...state,

                {

                    name: 'new',

                    id: nextToDo+=1

                }

            ]

        default:

            return state;

    }

}



export default reducer

商店.js


import reducer from './rootReducer'

import {applyMiddleware,createStore} from 'redux'

import logger from 'redux-logger'

import {persistStore, persistReducer} from 'redux-persist'

import storage from 'redux-persist/lib/storage'


const persistConfig ={

    key: 'root',

    storage

}

export const persistedReducer = persistReducer(persistConfig, reducer)

export const store = createStore(persistedReducer, applyMiddleware(logger));

export const persistor = persistStore(store);


export default {store, persistor}

索引.js:


import React, {Component} from 'react'

import {createStore} from 'redux'

import reducer from './rootReducer'

import 'bootstrap/dist/css/bootstrap.min.css'

import {Button} from 'react-bootstrap'

import {store} from './store'

import {connect} from 'react-redux'


class Index extends Component {

    render(){

    const {tasks} = this.props

    const add=()=>

    {

        store.dispatch(

            {

                type: 'add', 

            }

        )

    }

    store.subscribe(()=>console.log('your store is now', store.getState()))

    return (

        <div>

            {tasks.map(task=><div>{task.name}</div>)}

            <Button onClick={()=>add()}></Button> 

        </div>

    )

}

}

const mapStateToProps=(state)=>

{

    return{

        tasks: state

    }

}


export default connect(mapStateToProps)(Index)


jeck猫
浏览 114回答 1
1回答

冉冉说

尝试以这种方式声明状态:state = {&nbsp; tasks: [{}]}然后,在 Index.js 上,您可以通过执行以下操作将其传递给 props:const mapStateToProps=(state)=>{&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; tasks: state.tasks&nbsp; &nbsp; }}并在组件内部使用它props.tasks
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript