React Redux呈现商店状态更改,然后立即将应用刷新到初始状态

时间:2020-02-14 00:46:11

标签: javascript reactjs redux 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>
);

问题是,在所有这一切之下都有一个渲染,并且应该渲染新提交的书的列表(也存在但此处未包括)。它会花一秒钟的时间,然后又重新渲染到其初始状态(无书)。我想知道这是否是状态更改,但检查了所有源,仍然找不到我缺少的内容。另外,组合式减速器是有目的的。

更新 通过redux-logger进行检查,并且基本上是在做什么,当按下按钮时,它会更新状态,但是会刷新页面(并重新启动应用程序),像在开始状态一样显示它。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

好的,我解决了。问题是提交按钮上有一个type="submit"。更改为type="button",一切正常。