我用react redu做了一个todolist,但我不知道问题出在哪里。我想请你帮我检查问题。我非常感激。当页面第一次刷新时,会触发更改事件,并出现警告。如果第二个输入未刷新,则不会出现任何警告。请求解决方案
在此处输入图像描述
import React, { Component } from "react";
import { Input, Button, List } from "antd";
import store from "./store";
class TodoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this);
store.subscribe(this.handleStoreChange);
}
render() {
return (
<div style={{ marginTop: "10px" }}>
<div>
<Input
value={this.state.inputValue}
onChange={this.handleInputChange}
placeholder="todolist use antd design"
style={{ width: "300px", marginRight: "5px" }}
/>
<Button type="primary" onClick={this.handleSubmit}>
Submit
</Button>
</div>
<List
style={{ marginTop: "10px", width: "300px" }}
bordered
dataSource={this.state.list}
renderItem={(item) => <List.Item>{item}</List.Item>}
></List>
</div>
);
}
handleInputChange(e) {
const action = {
type: "change_input_value",
value: e.target.value,
};
store.dispatch(action);
}
handleStoreChange() {
this.setState(store.getState());
console.log("store changed");
}
handleSubmit() {
const action = {
type: "add_todo_item",
};
store.dispatch(action);
}
}
export default TodoList;
// here store folder
// store/index.js
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
// here store/reducer.js
const defaultState = {
inputValue: "",
list: [],
};
const reducer = (state = defaultState, action) => {
if (action.type === "change_input_value") {
const newState = JSON.parse(JSON.stringify(state)); // 深拷贝一个state
newState.inputValue = action.value;
return newState;
}
if (action.type === "add_todo_item") {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = "";
return newState;
}
console.log(state, action);
return state;
};
export default reducer;
我怀疑这是react或redux的版本。我不知道是什么原因造成的问题
TodoList.js第1部分
TodoList.js第2部分
reducer.js
错误图像
我认为您必须将构造函数代码放入componentDidMount钩子中。尤其是订阅一个
componentDidMount() { ... your constructor code }