3
rated 0 times
[
4]
[
1]
/ answers: 1 / hits: 5595
/ 4 Years ago, wed, june 3, 2020, 12:00:00
I'm using redux for statemanagement in react project and I access redux reducer file states in components like this :
Component.js
import { buyItem } from './itemActions';
import { connect } from 'react-redux';
function Comp(props) {
return (
<div>
<h3>{props.numOfItems}</h3>
<button onClick={() => props.buyItem('red')}>
Click
</button>
</div>
);
}
const mapState = (state) => {
return {
numOfItems: state.numOfItems
};
};
const mapDis = (dispatch) => {
return {
buyItem: (name) => dispatch(buyItem(name))
};
};
export default connect(mapState, mapDis)(Component);
And this is the reducer file which holds all the states :
import { BUY_ITEM } from './itemTypes';
const initialState = {
numOfItems: 0,
price: 0,
}
export const itemReducer = (state = initialState, action) => {
switch (action.type) {
case BUY_ITEM:
return {
...state,
price: state.price + state.products[action.payload].price,
};
default:
return state;
}
};
export default itemReducer;
And this is the redux action file :
import { BUY_ITEM } from './itemTypes';
export const buyItem = (name) => {
return {
type: BUY_ITEM,
payload: name
};
};
Now I want to access states and actions from index.js file but there is no export default method for it so I can import connect from redux and connect the index.js to redux .
this is the index.js file :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
How can I access states and call actions from index.js file ?
More From » reactjs