【问题标题】:Redux: Send Action Data to the StoreRedux:将操作数据发送到商店
【发布时间】:2024-04-19 20:55:02
【问题描述】:

作为新的 React 开发人员尝试使用 redux。我想发送一个动作,传递一个字符串,将文本属性更新为新状态。

这是我的做法。

const notesReducer = (state = 'Initial State', action) => {
 switch(action.type) {
   case "ADD_NOTE":
    return({
     text: action.text
    })
  default:
    return state;
 }
};

const addNoteText = (note) => {
  return ({
   type: "ADD_NOTE",
   text: note
   })
 };
 const store = Redux.createStore(notesReducer);
 console.log(store.getState());
 store.dispatch(addNoteText('Hello!'));
 console.log(store.getState());

动作创建者 addNoteText() 接受一个参数来传递给 text 属性。请帮忙

【问题讨论】:

    标签: redux


    【解决方案1】:

    这是我对这个挑战的解决方案,你真正需要改变的是你在 switch 语句中返回的内容:

     const ADD_NOTE = 'ADD_NOTE';
    
    const notesReducer = (state = 'Initial State', action) => {
      switch(action.type) {
        case ADD_NOTE:
    
        return action.text
    
        default:
          return state;
      }
    };
    
    const addNoteText = (note) => {
    
        return {
        type: ADD_NOTE,
        text: note
    }
    
    };
    
    const store = Redux.createStore(notesReducer);
    
    console.log(store.getState());
    store.dispatch(addNoteText('Hello!'));
    console.log(store.getState());
    

    【讨论】:

    • 我想通了..谢谢你花时间帮助我..#appreciate
    【解决方案2】:
    const notesReducer = (state = {
      text: ''
    }, action) => {
      switch(action.type) {
        case "ADD_NOTE": {
          return Object.assign({}, state, { text: action.text })
        }
        default:
          return state;
      }
     };
    
     const addNoteText = (note) => {
      return(
        {
          type: "ADD_NOTE",
          text: note
        }
      )
      };
    
      const store = Redux.createStore(notesReducer);
      console.log(store.getState());
      store.dispatch(addNoteText('Hello!'));
      console.log(store.getState());
    

    【讨论】:

    • 如果我设置了对象传播运算符,那将会起作用。这是在 freecodecamp.org 上,我必须想办法在不使用传播运算符的情况下处理这个问题
    • 见上面更新的代码。另一种方法是 Object.assign()。见*.com/questions/32925460/…
    • 要使用 es6,您可以将 babel 添加到您的 html 文件中。见*.com/questions/43931538/…