简体   繁体   English

React Redux -> Map 不是函数?

[英]React Redux -> Map is not a function?

So I am learning how to use redux and redux persist and currently I stuck at a problem right now.所以我正在学习如何使用 redux 和 redux persist,目前我遇到了一个问题。 Whenever I try to map my store's content, it throws an error saying TypeError: tasks.map is not a function and I don't really know why the problem is occuring.每当我尝试映射我商店的内容时,它都会抛出一个错误,指出TypeError: tasks.map is not a function而且我真的不知道为什么会出现问题。 I've googled around and tried debugging it, also tried to re-write the code a couple of time but it was all to no avail.我四处搜索并尝试调试它,还尝试重新编写代码几次,但都无济于事。 Here's my entire code: rootReducer.js这是我的全部代码: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

store.js商店.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}

Index.js:索引.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)

Try to declare state this way:尝试以这种方式声明状态:

 state = { tasks: [{}] }

Then, on Index.js, you can pass it to props by doing this:然后,在 Index.js 上,您可以通过执行以下操作将其传递给 props:

 const mapStateToProps=(state)=> { return { tasks: state.tasks } }

And use it inside the Component with props.tasks并在带有props.tasks的组件中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM