所以我正在学习如何使用 redux 和 redux persist,目前我遇到了一个问题。每当我尝试映射我商店的内容时,它都会抛出一条错误消息TypeError: tasks.map is not a function,我真的不知道为什么会出现这个问题。我用谷歌搜索并尝试调试它,也尝试重写代码几次,但都无济于事。这是我的全部代码:rootReducer.jsimport 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商店.jsimport 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)
1 回答
冉冉说
TA贡献1877条经验 获得超1个赞
尝试以这种方式声明状态:
state = {
tasks: [{}]
}
然后,在 Index.js 上,您可以通过执行以下操作将其传递给 props:
const mapStateToProps=(state)=>
{
return {
tasks: state.tasks
}
}
并在组件内部使用它props.tasks
添加回答
举报
0/150
提交
取消