首页 > 解决方案 > React redux 呈现存储状态更改,然后立即将应用程序刷新为初始状态

问题描述

用这个挣扎了一段时间,我按照所有的说明检查了很多次,这是代码:

const CREATE_BOOK = 'CREATE_BOOK';
const REMOVE_BOOK = 'REMOVE_BOOK';

const mapStateToProps = state => ({
  books: state,
});

const createBookAction = book => ({
  type: CREATE_BOOK,
  book,
});

const BookReducer = (state = [], action) => {
  switch (action.type) {
    case CREATE_BOOK:
      return [...state, action.book];
    case REMOVE_BOOK: {
      const index = state.findIndex(action.book);
      return state.slice(0, index).concat(state.slice(index + 1, state.length));
    }
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  books: BookReducer,
});

const store = createStore(rootReducer);

const initialState = {
  title: '',
  category: 'Action',
  id: () => (Math.random() * 100).toFixed(),
}

class BooksForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = initialState;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { target: { value }, target: { name } } = event;
    this.setState({
      [name]: value
    })
  }

  handleSubmit() {
    this.props.createBookAction(this.state);
    //this.setState(initialState);
  }

  render(){
    const categories = ['Action', 'Biography', 'History', 'Horror', 'Kids', 'Learning', 'Sci-Fi'];
    const categoriesBox = categories.map(cg => <option key={cg}>{cg}</option>);
    return (
      <form>
        <input name="title" onChange={this.handleChange} type="text" />
        <select name="category" onChange={this.handleChange}>{categoriesBox}</select>
        <button onClick={this.handleSubmit} type="submit">Submit</button>
      </form>
    );
  }
};

const App = props => {
  const { books: { books }, createBookAction } = props;
  return (
    <div>
      <BooksForm books={books} createBookAction={createBookAction} />
    </div>
  );
};

const Container = connect(mapStateToProps, { createBookAction })(App);

const AppWrapper = () => (
  <Provider store={store}>
    <Container />
  </Provider>
);

问题是,所有这些下面都有一个渲染,它应该与新提交的书一起渲染一个列表(也存在但不包括在这里)。它会持续一秒钟,然后再次重新呈现到它的初始状态(没有书)。我想知道这是否是状态变化,但检查了所有来源,但仍然找不到我缺少的东西。此外,组合减速器是故意的。

UPDATE 使用 redux-logger 检查,它所做的基本上是,当按下按钮时,它会更新状态,但随后会刷新页面(并重新启动应用程序),显示它就像处于开始状态一样。

标签: javascriptreactjsreduxreact-redux

解决方案


尝试移动<button onClick={this.handleSubmit} type="submit">Submit</button>

进入<form onSubmit={this.handleSubmit}>


推荐阅读