Задать вопрос

Как добавить значение в store redux?

// reducer
import {combineReducers} from 'redux';
const allReducers = combineReducers({
    messages: [],
    tech: "React "
});
export default allReducers;

// actions 
export const addMessage = item => {
    console.log(item);
    return  {
        type: 'ADD_MESSAGE',
        item
    }
}

// component 
...
submitMessage = event => {
      this.props.addMessage(event.target.value);
}
const mapStateToProps = state => {
  return {
    messages: state.messages
  };
}
const matchDispatchToProps = dispatch => {
  return bindActionCreators({addMessage: addMessage}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(Chat);

Как записать значение в messages в redux
  • Вопрос задан
  • 1408 просмотров
Подписаться 2 Простой Комментировать
Решения вопроса 1
rockon404
@rockon404 Куратор тега React
Frontend Developer
Например
import React, { useCallback, useRef } from 'react';
import ReactDOM from 'react-dom';
import { combineReducers, createStore } from 'redux';
import { Provider, connect } from 'react-redux';

// action type
const ADD_MESSAGE = 'ADD_MESSAGE';

// action creator
const addMessage = payload => ({
  type: ADD_MESSAGE,
  payload,
});

// reducer
const messages = (state = [], action) => {
  switch (action.type) {
    case ADD_MESSAGE:
      return [...state, action.payload];
    default:
      return state;
  }
};

// root reducer
const rootReducer = combineReducers({
  messages,
});

// store
const store = createStore(rootReducer);

const App = ({ addMessage, messages }) => {
  const inputRef = useRef(null);

  const handler = useCallback(() => {
    addMessage(inputRef.current.value);
    inputRef.current.value = '';
  }, [inputRef, addMessage]);

  return (
    <div>
      <ul>
        {messages.map((message, i) => (
          <li key={i}>{message}</li>
        ))}
      </ul>
      <input ref={inputRef} />
      <button onClick={handler}>Add Message</button>
    </div>
  );
};

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

const mapDispatchToProps = {
  addMessage,
};

const ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

const root = (
  <Provider store={store}>
    <ConnectedApp />
  </Provider>
);

const rootElement = document.getElementById('root');
ReactDOM.render(root, rootElement);

Пример с использованием redux-act
import React, { useCallback, useRef } from 'react';
import ReactDOM from 'react-dom';
import { combineReducers, createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import { createAction, createReducer } from 'redux-act';

// action creator
const addMessage = createAction('ADD_MESSAGE');

// reducer
const messages = createReducer({}, []);
messages.on(addMessage, (state, message) => [...state, message]);

// root reducer
const rootReducer = combineReducers({
  messages,
});

// store
const store = createStore(rootReducer);

const App = ({ addMessage, messages }) => {
  const inputRef = useRef(null);

  const handler = useCallback(() => {
    addMessage(inputRef.current.value);
    inputRef.current.value = '';
  }, [inputRef, addMessage]);

  return (
    <div>
      <ul>
        {messages.map((message, i) => (
          <li key={i}>{message}</li>
        ))}
      </ul>
      <input ref={inputRef} />
      <button onClick={handler}>Add Message</button>
    </div>
  );
};

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

const mapDispatchToProps = {
  addMessage,
};

const ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);

const root = (
  <Provider store={store}>
    <ConnectedApp />
  </Provider>
);

const rootElement = document.getElementById('root');
ReactDOM.render(root, rootElement);
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы