当 Main
组件加载到 Data 字段时,我有一个加载到 redux 状态的数据数组,如果我单击在我的按钮上触发 setLanguage
操作,它会更改语言,但也会清空数据数组。
如何防止更改语言时数据数组被清空?
终极版
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;
最佳答案
我已经更改了 dataReducer ,它现在存储数据并且在触发 SET_LANGUAGE 操作时不会消失
const dataReducer = (state = [], action) => {
switch (action.type) {
case 'FETCH_DATA':
return {
...state,
data: action.payload
};
default:
return state;
}
}
关于javascript - 当另一个 Action 被触发时,处于 redux 状态的对象消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009666/