I wanna use redux to do @pilchard's solution in this thread. It was not working in redux. where is going wrong with my codes?
action/index.js:
export const setCities = (city) => {
console.log(city)
return {
type: GET_CITIES_BY_SPECIAL_STATE,
payload: city
}
}
reducers/mainReducer.js
import {
GET_CITIES_BY_SPECIAL_STATE
} from '../actions/types';
const initialState = {
cities: []
}
const mainReducers = (state = initialState, action) => {
switch (action.type) {
case GET_CITIES_BY_SPECIAL_STATE:
return {...state, cities: state.cities.concat(action.payload)}
default:
return state;
}
}
export default mainReducers;
reducers/index.js:
import { combineReducers } from 'redux';
import mainReducers from "../reducers/main";
const reducers = combineReducers({
setCitiesReducer: mainReducers
});
export default reducers;
And this is how i use them:
import React, {useEffect} from "react";
import getCities from "../functions/getCities";
import RadioList from "./RadioList";
import {connect} from 'react-redux'
import {setCities} from '../redux/actions'
function ListOfStates(props) {
let labels = [],
cities = [];
useEffect(() => {
getCities(props.cityState).then((array) => {
for (let i = 0; i < array.response.length; i++)
cities.push(array.response[i]);
props.setCities([...cities]);
});
}, []);
return (<>
{
props.city.map((labels, index) =>
<RadioList active={(labels === props.active)} key={index} label={labels}/>)
}
</>);
}
const mapStatesToProps = state => {
return {
city: state.setCitiesReducer.city,
}
}
export default connect(mapStatesToProps, {setCities})(ListOfStates);
The error is:
TypeError: Cannot read property 'map' of undefined
question from:
https://stackoverflow.com/questions/65870050/push-an-array-elements-in-a-redux-state-returns-undefined 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…