В этом месяце я начал узнать больше о Redux, поэтому я решил написать базовый пост со своими знаниями о Redux с React. Я также учусь, так что поправьте меня, если есть ошибка.
Для Redux вам нужны некоторые вещи:
- REDUCER: функция, которая управляет вашими действиями и возвращает новое состояние;
- Действия: функция, которая говорит вашему редактору, что ему нужно делать;
- Магазин: государство, которое будет передано нашему заявлению;
Существует рекомендация сосредоточить наши переменные, которые определяют наши действия, определяя строку постоянной.
Давайте посмотрим на пример, сначала наш редуктор и действия:
// our constant with a string type
const ADD = 'ADD';
// our action creator, needs to be a pure function
const addMessage = (message) => {
return {
type: ADD,
message: message
}
}
// our reducer, also needs to be a pure function
const messageReducer = (state = [], action) => {
switch(action.type) {
case ADD :
// join the new message with the others
return [...state, action.message]
default :
return state
}
}
// need to import {createStore} from 'redux'
const store = createStore(messageReducer)
Вот и все, наше государство готово. Теперь нам нужно позвонить в наш компонент, чтобы прочитать состояние или отправить действие. Посмотрим, как мы можем это сделать:
import {useState} from 'react';
import { Provider, connect } from "react-redux";
const Presentational = (props) => {
const [input, setInput] = useState('')
const handleChange = (e) => {
setInput(e.target.value)
}
const handleSubmit = () => {
// we can call through the props because we use mapDispatchToProps below
props.submitNewMessage(input)
setInput('')
}
return (
Type a new message:
// we can read through the props because we use mapStateToProps below
{props.messages.map((message, index) => (
- {message}
))}
)
}
const mapStateToProps = (state) => {
return {messages: state}
};
const mapDispatchToProps = (dispatch) => {
// if we has another action, we will pass in this object
return {
submitNewMessage: (message) => {
dispatch(addMessage(message))
}
}
}
// connect all of this things in a Container wrapper
const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
const App = () => {
return (
// here the magic happens
)
}
Вот и все, я учусь, и это то, что я понял до сих пор, что вы думаете о Руксе?
Оригинал: “https://dev.to/ebraimcarvalho/understand-react-redux-introduction-5chn”