const actNewUser = postData => dispatch => {
let usercreating = postData;
axios
.post(page.path, postData)
.then(res => {
dispatch({
type: t.ADD_ALERT,
payload: { alertFor: 'newUser', alertType: 'success', alertMsg: msg }
});
})
.catch(err => {
dispatch({
type: t.ADD_ALERT,
payload: {
alertFor: 'newUser',
alertType: 'danger',
alertMsg: newAlertMsg
}
});
})
;
};
export { actNewUser };
Connecting the dots : action and states
import { actNewUser } from 'actions/newUserActions';
class PageUser extends Component {
onValidate = e => {
this.props.actNewUser({
username,
firstname,
lastname,
email,
authorities
});
}
}
const mapStateToProps = state => ({
status: state.newUser.status,
alertMe: state.notification.alertMe
});
export default connect(
mapStateToProps,
{ actNewUser }
)(PageUser);
const INIT_STATE = {
status: null
};
export default (state = INIT_STATE, action) => {
switch (action.type) {
case 'NEW_USER' : {
return {
...state,
status: action.status,
};
}
default: return state;
}
};
import { combineReducers } from 'redux';
import newUserReducer from './newUserReducer';
const reducers = combineReducers({
newUser: newUserReducer,
});
export default reducers;
import reducers from './reducers/index';
function configureStore(initialState) {
const store = createStore(
reducers,
initialState,
compose(applyMiddleware(...middlewares))
);
return store;
}
export { configureStore };
import React from 'react';
import { Provider } from 'react-redux';
import { configureStore } from './store';
const store = configureStore();
class MainApp extends React.Component {
render() {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route path='/' component={App} />
</Switch>
</ConnectedRouter>
</Provider>
);
}
}
export default MainApp;
class UserList extends Component {
renderList() {
return this.props.users.map(user => {
return (
<li key={user.id} onClick={() => this.props.selectUser(user)}>
{user.first} {user.last}
</li>
)
})
}
render() {
return <ul>{this.renderList()}</ul>
}
}
function mapStateToProps(state) {
return {
users: state.users,
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectUser: selectUser }, dispatch)
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(UserList)
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
export default connect(mapStateToProps)(MyComponent);
Think of connect() as the glue or interface between the component and the store. Any changes to the state will be reflected in the component because it is “connected” to mapStateToProps and that information is now made available to the component through a prop.
mapDispatchToProps
const mapDispatchToProps = () => {
return {
addThing: addThing,
doAnotherThing: doAnotherThing
}
}
As implied in its name, this function directs the dispatching or sending of an action by pointing it to an action creator. For example:
The action creator is made available to the component as a prop, which is usually tied to an event handler function contained in the component:
handleOnClick() {
this.props.addThing();
};
We also want the send that returned action to the store.
import { bindActionCreators } from 'redux';
...
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
addThing: addThing,
doAnotherThing: doAnotherThing
}, dispatch);
};
The bindActionCreators() function accepts the action creator and the store’s dispatch function as arguments, and returns a dispatch function that uses the return value of the action creator as its arguments.
Tying this all together is the connect() function, in which we pass mapDispatchToProps as a second argument. For example:
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
which will export a component that can both get the current state from the store, and dispatch an action to the store to trigger and update to the state.
https://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/
import{
connect
}from
'react-redux'
constTodoItem
=
({ todo, destroyTodo })
=>
{
return
(
<
div
>
{
todo
.text
}
<
span onClick
={destroyTodo
}>x
</span
>
</
div
>
)
}
constmapStateToProps
=
state
=>
{
return
{
todo
:state
.todos
[0]
}
}
constmapDispatchToProps
=
dispatch
=>
{
return
{
destroyTodo:
()
=>
dispatch({
type
:'DESTROY_TODO'
})
}
}
exportdefault
connect(
mapStateToProps
,
mapDispatchToProps
)(TodoItem
)
Common mistakes in redux
function updateNestedState(state, action) {
let nestedState = state.nestedState
// ERROR: this directly modifies the existing object reference - don't do this!
nestedState.nestedField = action.data
return {
...state,
nestedState
}
}
function updateNestedState(state, action) {
// Problem: this only does a shallow copy!
let newState = { ...state }
// ERROR: nestedState is still the same object!
newState.nestedState.nestedField = action.data
return newState
}