簡體   English   中英

React-Redux -> 為什么我的 reducer 沒有將更改后的狀態返回到索引頁面?

[英]React-Redux -> Why is my reducer not returning the changed state to the index page?

我有一個應用程序,它有一個減速器和一個索引頁,它應該將更改后的狀態返回到索引頁,在那里調用了對減速器的操作。 問題是,每當狀態發生變化並且我將其記錄在減速器文件中時,我可以看到它正在發生變化,但在索引頁面中看不到。 為什么會這樣? 這是我的減速器文件:

import React from 'react'

let nextToDo = 0;

const reducer =(state = {tasks: [{}]}, action)=>
{
    console.log('thats state', state)
    switch(action.type)
    {
        case 'add':
            return{
                ...state,
                    name: 'new',
                    id: nextToDo+=1
            }
        default:
            return state;
    }
}


export default reducer

這是我的 index.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
    console.log('thats tasks', tasks)
    const add=()=>
    {
        store.dispatch(
            {
                type: 'add', 
            }
        )
    }
    store.subscribe(()=>console.log('your store is now', store.getState()))
    return (
        <div>
            {tasks.map(task=><div><p>{task.name}</p></div>)} 
            <Button onClick={()=>add()}></Button> 
        </div>
    )
}
}
const mapStateToProps=(state = {tasks: [{}]})=>
{
    return{
        tasks: state.tasks
    }
}

export default connect(mapStateToProps)(Index)

據我了解您要做什么,問題就在這里:

            return{
            ...state,
                name: 'new',
                id: nextToDo+=1
        }

您將新值推送到狀態的根,然后您嘗試從state.tasks獲取它,但您的值只是在狀態中

你需要的是:

            return{
            ...state,
                tasks: [...state.tasks, { name: 'new', id: nextToDo+=1 }]
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM