繁体   English   中英

React redux 呈现 store state 变化,然后立即刷新应用到初始

[英]React redux renders store state change, immediately then refresh app to initial

在这个问题上挣扎了一段时间,我按照所有说明进行了检查并检查了很多次,这是代码:

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>
);

问题是,在所有这些下面有一个渲染,它应该用新提交的书渲染一个列表(也存在但不包括在这里)。 它会持续一秒钟,然后再次重新呈现为初始 state(无书籍)。 我想知道它是否是 state 更改但检查了所有来源但仍然找不到我丢失的东西。 此外,组合减速器是故意的。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM