javascript - 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 检查,它所做的基本上是,当按下按钮时,它会更新状态,但随后会刷新页面(并重新启动应用程序),显示它就像处于开始状态一样。
解决方案
尝试移动<button onClick={this.handleSubmit} type="submit">Submit</button>
进入<form onSubmit={this.handleSubmit}>
推荐阅读
- java - 正确的类层次结构
- process - 有没有人了解 TCPCopy 如何影响网络事务的性能?
- backtracking - 回溯导致相同的重复课程
- python - 风暴追踪算法
- azure - 具有特定映像名称的 Azure Devops 管道 Docker-Compose 构建
- amazon-web-services - 传递调用命令时无法在 Lambda 中执行 PowerShell
- c# - 为什么我现在在运行我的项目时会在 Windows.UI.Xaml 错误中收到“未找到方法”?
- inform7 - 如何更改命令的定义以引用不同的操作
- python - 有没有办法根据一系列列名访问数据框中的值?
- php - 我无法在 Cakephp 4 中进行身份验证,错误 500