我正在使用React和Redux构建Web应用程序。当我在该页面上设置状态然后通过类似this.props.book.bookTitle
的语句重新访问它时,Redux工作,但是,当我导航到另一个页面时,redux会丢失它的状态并默认为initialState。这是我的代码:
bookDuck.js:
const BOOK_SELECT = "book/SELECT";
const BOOK_DESELECT = "book/DESELECT";
const initialState = {
_id: "",
bookTitle: "",
bookCover: "",
bookAuthors: [],
bookDescription: ""
};
export default function reducer(state = initialState, action) {
switch(action.type) {
case BOOK_SELECT:
return Object.assign({}, action.book);
case BOOK_DESELECT:
return initialState;
}
return state;
}
export function selectBook(book) {
console.log(book);
return {type: BOOK_SELECT, book};
}
export function deselectBook() {
return {type: BOOK_DESELECT};
}
reducer.js:
import { combineReducers } from 'redux';
import user from './ducks/userDuck';
import book from './ducks/bookDuck';
export default combineReducers({
user,
book
});
store.js:
import { createStore } from 'redux';
import reducer from './reducer';
export default createStore(reducer);
index.js:
ReactDOM.render(
<center>
<Provider store={store}>
<Router history={browserHistory}>
<div>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/createAccount" component={CreateAccount} />
<Route path="/createBookGroup" component={CreateBookGroup} />
<Route path="/addMembers" component={AddMembers} />
</div>
</Router>
</Provider>
</center>
, document.getElementById('root'));
在下面的代码中,我设置了状态,然后导航到一个新窗口。
createBookGroup() {
let groupToCreateInfo = {
bookTitle: this.props.bookTitle,
bookCover: this.props.bookCover,
bookAuthors: this.props.bookAuthors,
bookDescription: this.props.bookDescription
}
console.log("Create book group is " + groupToCreateInfo.bookTitle);
store.dispatch(selectBook(groupToCreateInfo));
window.location = '/addMembers'
}
这是在childComponent中执行的。我在它的父组件中创建了一个测试按钮,该组件从商店访问this.props.book
而不导航到新页面,并且它在redux中访问属性就好了。但是只要我使用window.location
导航到新页面,redux值就会返回到它的初始状态:
const initialState = {
_id: "",
bookTitle: "",
bookCover: "",
bookAuthors: [],
bookDescription: ""
};
我在导出类时也连接到商店:
export default connect(state => ({book: state.book}))(AddMembers);
有谁知道我可能做错了什么?我很感激帮助。
答案 0 :(得分:6)
重新加载页面后,Redux状态不会保留。 window.location = '/addMembers'
导致页面重新加载,并且当您使用react-router时,这不是以编程方式导航到另一个页面的正确方法。而不是你应该使用this.props.history.push('/addMembers')
。
阅读this question的答案,了解如何以编程方式在react-router中导航。