Quelle: Andrés Gómez
Router
, Routes
, Route
,Link
(und ein paar andere)useParams
, useLocation
, useNavigation
npm install react-router-dom
Übergabe von State als Props an Komponenten, die diesen nur weiterreichen, ohne ihn selbst zu verwenden.
A Predictable State Container for JS Apps
npm install redux react-redux
getState
) und Änderung (dispatch
)type
und ggf. payload
newState = reducer(currentState, action)
)const remove = (id) => {
const action = {
type: 'REMOVE',
payload: id,
};
return action;
}
const onClick = {
const action = remove(4);
store.dispatch(action);
}
<button onClick={onClick}>Remove</button>
const initialState = [];
const favouritesReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD': {
return [...state, action.id];
}
case 'REMOVE': {
return state.filter(id => id !== action.id);
}
default: {
return state;
}
}
};
import { createStore } from 'redux';
const store = createStore(favouritesReducer);
<Provider store={store}> <App /> </Provider>
// App-State zu Props umformen
const mapStateToProps = state => ({ isLoggedIn: state.user.isLoggedIn });
// State-Änderungen zu Props umformen
const mapDispatchToProps = dispatch =>
({ login: () => dispatch({ type: 'LOGIN_USER' }) });
connect(mapStateToProps, mapDispatchToProps)(Komponente)
Lesen:
useSelector
(statt mapStateToProps
)Schreiben:
useDispatch
(statt mapDispatchToProps
)import { useSelector, useDispatch } from 'react-redux';
const isLoggedIn = useSelector(state => state.user.isLoggedIn);
const dispatch = useDispatch();
const login = () => dispatch({ type: 'LOGIN_USER' });
npm install redux-thunk
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(reducer, applyMiddleware(thunk));
useContext
useReducer