简体   繁体   English

无法从 Redux 存储中获取数据并在 UI 组件中更新

[英]Unable to fetch data from Redux store and update in UI component

I am new to Redux, am building a tracker app but I have been stacked for days.我是 Redux 的新手,正在构建一个跟踪器应用程序,但我已经堆积了好几天。 I would very much appreciate it if I could get help from you.如果我能得到您的帮助,我将不胜感激。 Thanks谢谢

store.js

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const initialState = { };
const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(...middleware), // store enhancer func
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()),
);

export default store;

waterReducer.js

import { GET_WATER,  ADD_WATER } from '../actions/types';

const initialState = {
  water: [],
  loading: false,
};

export default function (state = initialState, action) {                                           
  switch (action.type) {
    case GET_WATER:
      return {
        ...state,
        water: action.payload,
        loading: false,
      };
    case ADD_WATER:
      return {
        ...state,
        water: [action.payload, ...state.water || {}],
        loading: false,
      };
    default:
      return state;
  }
}


addWaterActions.js

const defaultURL = 'http://localhost:3000';

const myLibrary = JSON.parse(localStorage.getItem('myLibrary')) || []

const addWaters = waterData => async dispatch => {
  const apiConfig = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  };
  try {
    const water = await axios.post(`${defaultURL}/waters`, waterData, apiConfig);
    myLibrary.push(water.data);
    localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
    dispatch({
      type: ADD_WATER,
      payload: water.data,
    });
    return water.data;

  } catch(error) {
    dispatch({
      type: WATERS_ERRORS,
      payload: error
    });
  }
};

addWaterComponent.js

import { addWaters } from '../../redux/actions/waterActions';

const AddWater = ({ addWaters }) => {
  const [formData, setFormData] = useState({
    amount: '',
    total: '',
  });
  const {
    amount, total,
  } = formData;
  const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });

  const onSubmit = e => {
    e.preventDefault();
    addWaters({
      id: uuidv1(),
      amount,
      total,
    });
  };

  return (
    <>
      <AddWrap>
        <TrackWater>
          Add Water
        </TrackWater>
        <CenterW>
          
          <FormWrap onSubmit={onSubmit}>
            <AmountInp
              type="number"
              name="amount"
              value={amount}
              onChange={onChange}
              placeholder="Amount"
              required
            />
            <TotalInp
              type="number"
              name="total"
              placeholder="Water Target"
              value={total}
              onChange={onChange}
              required
            />
            <SubmitData type="submit" onSubmit={onSubmit}>
              Add Water to Data
            </SubmitData>
          </FormWrap>
        </CenterW>
      </AddWrap>
      <Footer />
    </>
  );
};

AddWater.propTypes = {
  addWaters: PropTypes.func.isRequired,
  water: PropTypes.array.isRequired,
};

const mapStateToProps = state => ({
  water: state.water.water,
});

export default connect(mapStateToProps, { addWaters })(AddWater);


Redux dev tools screenshot localStorage screenshot What this code has achieved 1. Dispatch data to localStorage 2. Dispatch data to Redux dev tools Redux dev tools screenshot localStorage screenshot这段代码实现了什么 1. Dispatch data to localStorage 2. Dispatch data to Redux dev tools

My problem: I want to read the data from the store to the component, but when I console.log(store.getState().water);我的问题:我想从商店读取数据到组件,但是当我 console.log(store.getState().water); the state is empty.状态为空。 I really need your help guys.我真的需要你们的帮助。 Thanks in advance提前致谢

The store the js is can be configured this way const store = createStore(rootReducer,initialState, applyMiddleware(thunk)); js 所在的商店可以这样配置const store = createStore(rootReducer,initialState, applyMiddleware(thunk)); the applyMiddleware is just an enhancer to enable you dispatch an action to your store via the reducer. applyMiddleware 只是一个增强器,使您能够通过 reducer 将操作发送到您的商店。 console.log( action.playload ), then make sure in the reducer you equate the actual data to the water attribute. console.log( action.playload ),然后确保在减速器中将实际数据等同于水属性。 I suspect case GET_WATER: return { ...state, water: action.water, loading: false, };我怀疑case GET_WATER: return { ...state, water: action.water, loading: false, }; should work, I suspect that is where the error is coming from, don't forget to map state to props to access data.应该可以工作,我怀疑这是错误的来源,不要忘记将状态映射到道具以访问数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM