为了账号安全,请及时绑定邮箱和手机立即绑定

怎么初始化react-redux生成的store

怎么初始化react-redux生成的store

江户川乱折腾 2019-02-28 18:19:44
在页面第一次加载的时候我已经把react-redux生成的store绑定到了provider上。ReactDom.render(    <Provider store={store}>        {AppealRoutes}    </Provider>,    document.getElementById('appeal-container'));经过几个页面后,store里面已经保存了页面的状态数据。但是我如果有在子组件初始化store的数据,该怎么做呢?我就是想在子组件内部去将保存状态数据的store初始化成空的{}。
查看完整描述

2 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

在那个子组件里,传一个action给reducer,这个action就是你要的空{},{...state,A:{},B:{}....}


查看完整回答
反对 回复 2019-03-06
?
富国沪深

TA贡献1790条经验 获得超9个赞

假设你有一个子组件 Child,你想将数据存在 store 下的 child。


当前的 store 状态是


{

    // other data

    child: {

        // child data

    }

}

在 redux 的世界里, store 的更改必须由 reducer function 来更改,此时就需要发送一个类似 resetChildData 的action,简写如下


export resetChildData = () => {

    type: 'REST_CHILD_DATA',

}

然后需要书写对应的 reducer 来了真正的清除数据


const INIT_STATE = {}


export const childReducer = (state, action) => {

    switch(action.type) {

        case 'REST_CHILD_DATA':

            return INIT_STATE

        default:

            return state

    }

}

注意此时的 rootReducer 需要绑定这个 childReducer


const rootReducer = {

    child: ChildReducer,

}

至此,在 Child 组件中,将 action 通过 connect 函数传入


import resetChildData from '../actions/child'


Class Child extends Component {

}


export default connect(

    null,

    {

        resetChildData,

    }

)(Child)

在组件任何地方就可以使用 this.props.resetChildData 来清空 store 下的 child


查看完整回答
反对 回复 2019-03-06
  • 2 回答
  • 0 关注
  • 1696 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号