导航到另一个页面时,Redux会丢失状态

her*_*mt2 0 javascript reactjs redux react-redux

我正在使用React和Redux构建Web应用程序.当我在该页面上设置状态然后通过类似的语句重新访问它时,Redux工作this.props.book.bookTitle,但是,当我导航到另一个页面时,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};
}
Run Code Online (Sandbox Code Playgroud)

reducer.js:

import { combineReducers } from 'redux';
import user from './ducks/userDuck';
import book from './ducks/bookDuck';

export default combineReducers({
  user,
  book
});
Run Code Online (Sandbox Code Playgroud)

store.js:

import { createStore } from 'redux';
import reducer from './reducer';

export default createStore(reducer);
Run Code Online (Sandbox Code Playgroud)

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'));
Run Code Online (Sandbox Code Playgroud)

在下面的代码中,我设置了状态,然后导航到一个新窗口.

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'
  }
Run Code Online (Sandbox Code Playgroud)

这是在childComponent中执行的.我在它的父组件中创建了一个测试按钮,可以this.props.book从商店访问而无需导航到新页面,它可以很好地访问redux中的属性.但是只要我使用导航到新页面window.location,redux值就会返回到它的初始状态:

const initialState = {
  _id: "",
  bookTitle: "",
  bookCover: "",
  bookAuthors: [],
  bookDescription: ""
};
Run Code Online (Sandbox Code Playgroud)

我在导出类时也连接到商店:

export default connect(state => ({book: state.book}))(AddMembers);

有谁知道我做错了什么?我很感激帮助.

Tha*_*ara 6

重新加载页面后,Redux状态不会保留.window.location = '/addMembers'导致页面重新加载,并且当您使用react-router时,这不是以编程方式导航到另一个页面的正确方法.而不是你应该使用this.props.history.push('/addMembers').

阅读此问题的答案,以了解如何以编程方式在react-router中导航.