2017-05-29 78 views
0

我正在使用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);

有誰知道我可能會做錯什麼?我很感激幫助。

+0

我認爲問題在這裏'window.location ='/ addMembers''這使得整個頁面重新加載,從而導致狀態被重置。 –

+0

React有另外一種選擇嗎? – hermt2

回答

2

重新加載頁面後,Redux狀態不會保留。 window.location = '/addMembers'會導致頁面重新加載,並且當您使用react-router時,它不是以編程方式導航到另一個頁面的正確方法。而不是你應該使用this.props.history.push('/addMembers')

閱讀this question的答案,以瞭解如何以編程方式在react-router中導航。

+0

明白了。謝謝 – hermt2

相關問題