我正在使用React和Redux構建Web應用程序。當我在該頁面上設置狀態時,Redux可以工作,然後通過像this.props.book.bookTitle
這樣的語句重新訪問它,但是當我導航到另一個頁面時,redux會丟失它的狀態並且默認爲initialState。這裏是我的代碼:Redux在導航到另一頁時失去狀態
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
了新的一頁,在終極版值將返回到它的初始狀態:
const initialState = {
_id: "",
bookTitle: "",
bookCover: "",
bookAuthors: [],
bookDescription: ""
};
我也連接到店裏出口類這樣的時候:
export default connect(state => ({book: state.book}))(AddMembers);
有誰知道我可能會做錯什麼?我很感激幫助。
我認爲問題在這裏'window.location ='/ addMembers''這使得整個頁面重新加載,從而導致狀態被重置。 –
React有另外一種選擇嗎? – hermt2