当Main
组件加载到“数据”字段中时,我有一个数据数组加载到redux状态,如果我单击按钮,我的默认应用程序语言也存储在redux状态触发setLanguage
操作将更改语言,但也将清空数据数组。
更改语言时如何防止清空数据数组?
redux
data: []
language: english
Main.js
class Main extends React.Component {
componentDidMount() {
this.props.fetchData()
}
render() {
const {language} = this.props
const e = language === 'english'
const p = language === 'polish'
return(
<Wrap>
<Router>
<ScrollToTop>
<Header />
<Wrap>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/reviews" component={Reviews} />
<button onClick={this.props.fetchData}>click</button>
{/* <Route exact path="/reviews/:catId" component={Reviews} />
<Route exact path="/reviews/:catId/:slug" component={Review} /> */}
{/* <Route exact path="/" component={Home} /> */}
{/* <ScrollToTop path="/reviews/:catId" component={Review} /> */}
{/* <ScrollToTop path="/another-page" component={Reviews} /> */}
</Switch>
</Wrap>
</ScrollToTop>
</Router>
</Wrap>
)
}
}
const mapStateToProps = state => ({
language: state.language
});
export default connect(mapStateToProps, actionCreators)(Main);
MainActions.js
import axios from 'axios'
import {
FETCH_DATA
} from '../../Constants'
export function fetchData() {
return dispatch =>
axios
.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
dispatch({ type: FETCH_DATA, payload: response.data });
})
.catch((err) => {
console.error(err);
});
}
dataReducer.js
import {
FETCH_DATA
} from '../Constants'
const dataReducer = (state = [], action) => {
return{
...state,
data: action.payload
}
}
export default dataReducer;
Header.js
class Header extends React.Component {
render() {
const {language} = this.props
const e = language === 'english'
const p = language === 'polish'
return (
<Wrapper>
<button onClick={()=>this.props.setLanguage('english')}>english</button>
<button onClick={()=>this.props.setLanguage('polish')}>polish</button>
<div>
{e && <div>language is english</div>}
{p && <div>language is polish</div>}
</Wrapper>
)
}
}
const mapStateToProps = state => ({
language: state.language
});
export default connect(mapStateToProps, actionCreators)(Header);
headerActions.js
import {
SET_LANGUAGE
} from '../../Constants'
export function setLanguage(language) {
return {
type: SET_LANGUAGE,
language
}
}
languageReducer.js
import {
SET_LANGUAGE
} from '../Constants'
const initialState = 'english'
const languageReducer = (state = initialState, action) => {
switch (action.type) {
case SET_LANGUAGE:
action.language
default:
return state;
}
};
export default languageReducer;
combineReducers.js
const rootReducer = combineReducers({
language: languageReducer,
data: dataReducer
});
export default rootReducer;
答案 0 :(得分:0)
我已经更改了dataReducer,它现在存储数据并且在触发SET_LANGUAGE操作时不会消失
const dataReducer = (state = [], action) => {
switch (action.type) {
case 'FETCH_DATA':
return {
...state,
data: action.payload
};
default:
return state;
}
}