gpt4 book ai didi

javascript - Redux,获取所有状态而不是我通过的状态

转载 作者:行者123 更新时间:2023-11-29 16:37:26 24 4
gpt4 key购买 nike

我在 react-redux 中遇到了一个奇怪的问题,我得到的是所有状态而不是我通过的状态这是我的代码:

Action.js

import socketIOClient from 'socket.io-client'

const DATA_URL = "LINK TO API";
export const GET_DATA ='GET_DATA';
export const LIVE_DATA = 'LIVE_DATA';
const parseData= arr => arr.reverse().map((i)=>([i[0],i[1],i[3],i[4],i[2],i[5]]))

export const getData = () => dispatch =>{
fetch(DATA_URL).then(res => res.json())
.then(data => dispatch({
type:GET_DATA,
payload:parseData(data)
}
))
}
export const getLive = () => dispatch => {
var checkTime=0;
const socket = socketIOClient('http://localhost:3001');
socket.on("candle",(res)=>{
if(checkTime <= res[0]){
checkTime = res[0];
dispatch({
type:LIVE_DATA,
payload:res
})
}
})
}

api.js

import {GET_DATA,LIVE_DATA} from '../actions/index';
const INITIAL_STATE = {all:[],live:[]}

export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_DATA:
return Object.assign({},state,{all:action.payload})
case LIVE_DATA:
return Object.assign({},state,{live:action.payload})
default:
return state;
}
}

reducer.js

import { combineReducers } from 'redux';
import all from './api';
import live from './api';
const reducers = combineReducers({
candle:all,
livedata:live
});
export default reducers;

正如你所看到的,我将all传递给candle,将live传递给livedata

但在我的 Reduxdevtools 中,我可以访问蜡烛和实时数据中的所有内容,如屏幕截图所示

enter image description here

这就是我在组件上调度操作的方式

App.js

const mapStateToProps = state => ({
data: state.candle.all,
live: state.livedata.live
})

有人可以告诉我需要更改什么以便我只能访问

live 处于 livedata 状态,all 仅处于 candle 状态

谢谢

最佳答案

发生这种情况是因为您正在访问相同的 reducer ,但名称不同。您应该为每个创建单独的 reducer 。

像这样:

candleReducer.js

import {GET_DATA} from '../actions';

const INITIAL_STATE = { all:[] }

export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_DATA:
return Object.assign({},state,{all:action.payload})
default:
return state;
}
}

liveReducer.js

import {LIVE_DATA} from '../actions';

const INITIAL_STATE = { live:[] }

export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case LIVE_DATA:
return Object.assign({},state,{ live:action.payload })
default:
return state;
}
}

然后将它们导入到组合 reducer 中:

import { combineReducers } from 'redux';
import all from './candleReducer';
import live from './liveReducer';
const reducers = combineReducers({
candle:all,
livedata:live
});
export default reducers;

关于javascript - Redux,获取所有状态而不是我通过的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49998669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com