reducer有返回值,而且无论reducer的state怎么变化,但是打印的store时钟为空的{}

其实有好几个问,卡了好久了不知道什么原因
1.两个reducer的state都有值的情况下
store.subscribe(() => {

console.log("================监听store变化:"+JSON.stringify(store));

});
打印的值一直是空的{}。

2.点击导航时候在Mount组件的时候去请求数据,然后执行store.dispatch(initUserAction(res)),初始化reducer的state,state有数据,但是store.subscribe里面答应的store一直是空的。
这个是加载组件的时候初始化的代码

componentWillMount(){
        const {store} = this.context;
        fetch("http://localhost:3001/book")
        .then(res => res.json())
        .then(res => {
            store.dispatch(initBookAction(res));
        });
    }

这个是reducer的代码

const initialState = {
    data : []
};

function bookReducer(state=initialState ,action){
    switch(action.type){
        case 'INIT_BOOK_ACTION':
            console.log("=====初始化bookReducer:"+JSON.stringify(state));
            return Object.assign({},state,{
                data : [...action.payload]
            })

        case 'ADD_BOOK_ACTION' : 
            return Object.assign({},state,{
                data : state.data.push(action.payload)
            })

        case 'DELETE_BOOK_ACTION' :
            return Object.assign({},state,{
                data : state.data.filter(item => item.id != action.payload.id)
            })

        case 'UPDATE_BOOK_ACTION' :
            return Object.assign({},state,{
                data : state.data.map(item => {
                    if(item.id == action.payload.id){
                        return Object.assign({},item,action.payload);
                    }else{
                        return item;
                    }
                })
            })
        default:
            return state
    }
}

export default bookReducer;

3.我加载的table的数据是mapStateToProps传递过来的数据,既然store为空,为什么container组件中给mapStateToProps传递的state依然可以取到数据state.bookReducer.date,然后在table中展示出来数据呢?

这个是render table的主要代码

render(){
        const { bookList, deleteBook } = this.props; //connect传递的props
        const { title,visible ,confirmLoading } = this.state;
        //console.log("===================booklist props:"+JSON.stringify(this.props));
        
        const columns = [{
            title : '图书编号',
            dataIndex : 'id'
        },{
            title : '名称',
            dataIndex : 'name'
        },{
            title:'价格',
            dataIndex:'price'
        },{
            title:'借阅人编号',
            dataIndex:'owner_id'
        },{
            title:'操作',
            render : (text,record) => (
                <span type="ghost">
                    <Button size="small" onClick={() => this.editHandle(record)}>编辑</Button>
                    <Divider type="vertical" />
                    <Popconfirm title="确定要删除吗?" onConfirm={() => deleteBook(record)}>
                        <Button size="small" >删除</Button>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <div>
                <div>
                    <SearchInput addHandle={this.addHandle.bind(this)}/>
                </div>
                <Table columns={columns} dataSource={bookList}/>
                <Modal 
                    title={title}
                    visible= {visible}
                    confirmLoading = {confirmLoading}
                    onCancel = {() => this.cancelHandle()}
                    footer = {null}
                >
                    <FormLayout record={this.state.formData} comfirmHandle={this.comfirmHandle.bind(this)}/>
                </Modal>
            </div>
        );
    }

这个是创建container组件的代码

import { connect } from 'react-redux';
import BookList from '../components/BookList';
import { deleteBookAction , addBookAction ,updateBookAction } from '../actions/bookActions';

const mapStateToProps = (state) => {
    return {
        bookList : state.bookReducer.data
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        deleteBook : (id) => {
            dispatch(deleteBookAction(id))
        },
        addBook : (data) => {
            dispatch(addBookAction(data))
        },
        editBook : (data) => {
            dispatch(updateBookAction(data))
        }
    }
}
const BookListContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(BookList);

export default BookListContainer;

代码有点多我把github地址粘上来,麻烦各位大神帮我看一下,谢谢~

github地址:https://github.com/hesisi/rea...

阅读 3.7k
2 个回答
console.log("================监听store变化:"+JSON.stringify(store));

变化是变化了,不过姿势不对。

store.subscribe(() => {
  console.log(store.getState()); // 返回应用当前的状态树
}

reducer没有注册到store

你要从“本源”上去看问题,先看看你的entry.js

ReactDOM.render(
    <Provider store={store}>
        // routes
    </Provider>

去看看store从哪里来的。
最后追溯到一个整个应用的reducer文件的汇总注册文件reducer.js:

import { combineReducers } from "redux";
import { routerReducer } from "react-router-redux";

import * as yourComponentReducer from './path/reducers.ts';

export default combineReducers({
  routing: routerReducer,
  ...yourComponentReducer,
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题