score:2
mapdispatchtoprops
provides you a way to connect
your action creators
to your components. let's assume you have an action creator which increments a counter
state
export const change = value =>({
type: 'change_fruit',
fruit : value
})
and you want value
to be passed from one of your components. first use connect
hoc in this component like you're already doing. now you need to import incrementcounter
from your actions
folder
import { change as changefruit } from './actions/fruit'
now use mapdispatchtoprops
like this
const mapdispatchtoprops = dispatch =>({
change : fruit => dispatch(changefruit(fruit))
})
now you have an action creator
serialized inside your component's props
and when you call props.increment(2)
this will be the equivalent to call
dispatch(changefruit('apple'))
here is why you should always do props.increment
instead of directly call dispatch
inside your component.
so the full implementation inside your component could be like this
import { change as changefruit } from './actions/fruit'
class component extends react.component{
render(){
const { fruit, change } = this.props
return(
<>
<div>{fruit}</div>
<button onclick={() => change('orange')}>change to orange</button>
</>
)
}
}
const mapstatetoprops = state =>({
fruit : state.fruit
})
const mapdispatchtoprops = dispatch =>({
change : fruit => dispatch(changefruit(fruit))
})
export default connect(mapstatetoprops, mapdispatchtoprops)(component)
your reducer should look like this
const initialstate = {
fruit: 'apple'
}
export const reducer = (state = initialstate, action) =>{
switch(action.type){
case 'change_fruit' : return{
...state,
fruit : action.fruit
}
default : return state
}
}
score:0
an "action" is just a plain object that describes some sort of change you want to happen in your store. so in your case you want to add text to your string, such an action might look like:
{
type: 'add_text',
value: 'red delicious'
}
an action creator is nothing more than a function that returns such a plain object. notice we can generalise the action creator, so you can pass in the string to add, rather than have it hard coded as 'red delicious'.
const addtext = value => ({ type: 'add_text', value })
in order to 'send' this action to the reducers, it needs to be passed to dispatch
function that redux provides. e.g. this would dispatch the action:
const action = addtext('red delicious') // create the plain action object
dispatch(action) // send it to the reducers
that can get kind of tedious to write out manually all the time, so mapdispatchtoprops
helps with that. it's a function you provide to connect
that does the above all in one place, leaving the rest of your component code un-cluttered. redux calls it internally to generate the props for your connected component. so when you do,
const mapdispatchtoprops = dispatch => ({
addtext: value => {
// same code as above:
const action = addtext('red delicious')
dispatch(action)
}
})
in your component you can call
props.addtext('red delicious')
score:0
look when use the connect function in the app it takes 2 arguments the first is the state current and the second argument is the dispatch that specifies what type of action that will be implemented is the specific action the dispatch depended on the despatch will be called the specific action that link by reducer that implements in provider in-store when use
<provider store={store}>
which the reducer that created by the const store=createstore(rootreducer)
const mapdispatchtoprops = (dispatch) => {
return{
example look this is dispatch that well happened it will call specif action bu use key type
this == store.dispatch(constants.widithroup)
the first is key or name of the handle when you want to implement :(input that enters fro this dispatch and=> it call store.dispatch(name of handel) )
widthroup: (balance) => dispatch({ type: constants.widithroup ,balance}),
deposit: (balance) => dispatch({ type: constants.deposit,balance }) }
}
}
score:0
basically i am answering for the part where you have confusion:
return {
what goes in here?
}
ideally, if you think as class concept, let's say you have a class that facilitates to choose and save your favorite color selection.
so, all you want is to create a class component and define a method saveselection that should save selection to store. and, who ever wants to get that selection or see your selected colors they can access from store.
back to redux, the rule says, you can not update the state of store directly. you have to dispatch an action.
so, if i already have a decided to create a method saveselection for that purpose, what should i do, so that it should dispatch an action.
may be something like:
class colorselector {
saveselection () {
dispatch(action); //dispatch is some way to dispatch an action
}
}
but, action is not just a command or text or a value, we need to specify, the type of action (because reducer need to identify which data it need to update based on action) and the data i want to save. that will make sense of an action.
so, i want something like:
//i pass my selected color to saveselection method and that should save
saveselection(datatoupdate) {
dispatch({type: actiontype, data: datatoupdate})
}
one thing may be going inside your head -> how will i get dispatch and how did i just use it here? that will get clear in a sec, but first lets replace the dispatch arguments which we can write like:
saveselectionaction(datatoupdate) {
return {type: actiontype, data: datatoupdate}
}
and our method would be like:
saveselection(datatoupdate) {
dispatch(saveselectionaction(datatoupdate))
}
and saveselectionaction becomes the action creator part. now comes the dispatch part. so, lets wrap this method with another method which provides dispatch and expose saveselection
anothermethodwhichpassesdispatch(dispatch) {
// unleash the power of closure
return {
saveselection: saveselection(datatoupdate) {
dispatch(saveselectionaction(datatoupdate))
}
}
}
or more correctly
// method to map dispatching action to components props
anothermethodwhichpassesdispatch(dispatch) {
// return list of your created action you want as props
return {
// name it whatever you want and that will be a void method passing data
saveselection: (datatoupdate) => {
// pass the action creator's result which is defined above
// or, exported from a separate file
dispatch(saveselectionaction(datatoupdate))
}
}
}
now pass this method as argument to connect hoc and that will map saveselection to a props and provide dispatch to your method.
connect(mapstatetoprops, anothermethodwhichpassesdispatch)(<container>)
or we can rename it as mapdispatchtoprops
.
now go back to your class's saveselection method and do like:
saveselection = (selectedcolor) => {
this.props.saveselection(selectedcolor);
}
that's it.
Source: stackoverflow.com
Related Query
- How can I dispatch a change in the constructor?
- How can I dispatch a state change to redux when calling it from a function inside the component?
- material UI - How can I change the font size of the label in FormControlLabel
- How can i change the cell colour in ANTD table according to the value?
- How can I change the color of a Link in React with Material-UI?
- (Next.js) How can I change the color of SVG in next/image?
- How can I change the format for react datepicker days of the week?
- How can I change the width of Material UI Autocomplete popover
- how can I react-bootstrap change the color of the tabs
- In redux-observable - How can I dispatch an action "mid-stream" without returning the value of that action?
- How can I change icon in the KeyboardTimePicker (material-ui-pickers)?
- How can I change the label size of a material ui TextField?
- How can I change the styles of the react-toastify popup message?
- How can I handle the change event with React-Hook-Form?
- How can I setup a local environment to work with the latest SameSite cookie change to Chrome?
- How can I dynamically change the value of a CSS property in React?
- How can I change the color of material-table icons of onRowAdd, onRowUpdate, onRowDelete?
- How can I change the default port in react from 3000 to another port?
- How can I properly change the title of react-bootstrap DropdownButton on click?
- React-Datepicker: How can I change the navigation arrows?
- How can I change the color of the ANT Design's Spin component?
- How can I change the icon in material-ui date picker for React
- How can I change the checkbox styles and icons when hover on it in Material-UI React?
- How can I check the return value of dispatch in redux hook
- How can I change the underline color of MaterialUI's React Tabs component?
- Material UI: How can I change the border color of the Select component?
- How can change the clone of an array and not change the original array in reactjs
- How can I change remove the filter icon when using the material-table library?
- ReactJS: How can I change the link preview of a URL?
- How can I change a child's state from the parent component
More Query from same tag
- TableData.js:57 DELETE https://clientdata-dd88a-default-rtdb.firebaseio.com/userData.json/:$%7Bid%7D
- React Router: How to stop redirecting until API returns a response?
- Reducer updates state object which it should not be able to access
- Cannot perform a React state update on an unmounted component. Indicates memory leak
- How to pass arguments to function and still access event to prevent default
- React Hooks. Solutions for getting value of useState after setting method
- "window.innerWidth < 768" in Next.js with Framer Motion
- React & TypeScript: Functional Components that Are Not Arrow Functions
- Persist some attributes with redux-persist does not work
- this.setState is not updating the state property
- Looping and rendering in reactjs
- React useState hook: passing setter to child- functional update, callback and useCallback
- Use CSS/Jquery calc function in React Js
- React-router how to load nested children within children?
- how can I send props to other file?
- how to render list in react using api
- Confused about how to create a ref if there is no forward ref?
- In React, how do I name a field of my form that is part of an array?
- Passing a Redux Action to a child component with props
- Can I have one onClick function to change different state values in React-js
- Get parent VALUE on React-select grouped options
- React-Redux. Redux state changes but data not being refreshed on page
- React state is getting overwritten when coming back from child component
- Add multiple classes in if statements in React
- how fix Element implicitly has an 'any' type because expression of type 'string' can't be used to index type?
- Passing Function parameter to another component in react
- Equivalent of scss @import for styled-components?
- How to return text for an individual correct or wrong answer state in React
- How do I get a for loop working within a functional component reactJS
- Visual Studio Code [eslint] Delete 'CR' [prettier/prettier] on windows