我是新手,刚开始学习反应。我遇到的问题是,当我添加元素时,我不会使整个列表过载。尽管更新和删除工作正常,但更改会立即被覆盖。重新加载页面后,列表中会出现一个新项目。
事实证明,当我安装组件并将其拉出时,会得到一个列表,而当我添加新元素时,状态不知道其更改。可能您需要立即将fetchNotes()带给我的状态转移到该状态。如何正确地创建它,请告诉我,我已经尝试过使用willMount()并进行各种操作,但是要么我设法填充了状态,但是然后我不起作用this.state.map( )或任何其他废话... 我添加项目的方法:
class Note extends Component {
state = {
text: "",
updateNoteId: null,
};
componentDidMount() {
this.props.fetchNotes();
};
resetForm = () => {
this.setState({text: "", updateNoteId: null});
};
selectForEdit = (id) => {
let note = this.props.notes[id];
this.setState({text: note.text, updateNoteId: id});
};
submitNote = (e) => {
e.preventDefault();
if (this.state.updateNoteId === null) {
this.props.addNote(this.state.text).then(this.resetForm);
} else {
this.props.updateNote(this.state.updateNoteId,
this.state.text).then(this.resetForm);
}
this.resetForm();
};
render() {
return (
<div>
<div style={{textAlign: "right"}}>
{this.props.user.username} (<a onClick={this.props.logout}>logout</a>)
</div>
<h3>Add new note</h3>
<form onSubmit={this.submitNote}>
<input
value={this.state.text}
placeholder="Enter note here..."
onChange={(e) => this.setState({text: e.target.value})}
required />
<input type="submit" value="Save Note" />
</form>
<button onClick={this.resetForm}>Reset</button>
<h3>Notes</h3>
<table>
<tbody>
{this.props.notes.map((note, id) => (
<tr key={`note_${id}`}>
<td>{note.text}</td>
<td><button onClick={() => this.selectForEdit(id)}>edit</button></td>
<td><button onClick={() => this.props.deleteNote(id)}>delete</button></td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
const mapStateToProps = state => {
return {
notes: state.notes,
user: state.auth.user,
}
};
const mapDispatchToProps = dispatch => {
return {
fetchNotes: () => {
dispatch(notes.fetchNotes());
},
addNote: (text) => {
return dispatch(notes.addNote(text));
},
updateNote: (id, text) => {
return dispatch(notes.updateNote(id, text));
},
deleteNote: (id) => {
dispatch(notes.deleteNote(id));
},
logout: () => dispatch(auth.logout()),
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Note);
减速器/
const initialState = [];
export default function notes(state=initialState, action) {
let noteList = state.slice();
switch (action.type) {
case 'FETCH_NOTES':
return [...state, ...action.notes];
case 'ADD_NOTE':
return [...state, ...action.note];
case 'UPDATE_NOTE':
let noteToUpdate = noteList[action.index];
noteToUpdate.text = action.note.text;
noteList.splice(action.index, 1, noteToUpdate);
return noteList;
case 'DELETE_NOTE':
noteList.splice(action.index, 1);
return noteList;
default:
return state;
}
}
动作
export const fetchNotes = () => {
return (dispatch, getState) => {
let headers = {"Content-Type": "application/json"};
let {token} = getState().auth;
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/notes/", {headers, })
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data};
})
} else {
console.log("Server Error!");
throw res;
}
})
.then(res => {
if (res.status === 200) {
return dispatch({type: 'FETCH_NOTES', notes: res.data});
} else if (res.status === 401 || res.status === 403) {
dispatch({type: "AUTHENTICATION_ERROR", data: res.data});
throw res.data;
}
})
}
};
export const addNote = text => {
return (dispatch, getState) => {
let headers = {"Content-Type": "application/json"};
let {token} = getState().auth;
if (token) {
headers["Authorization"] = `Token ${token}`;
}
let body = JSON.stringify({text, });
return fetch("/api/notes/", {headers, method: "POST", body})
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data};
})
} else {
console.log("Server Error!");
throw res;
}
})
.then(res => {
if (res.status === 201) {
return dispatch({type: 'ADD_NOTE', note: res.data});
} else if (res.status === 401 || res.status === 403) {
dispatch({type: "AUTHENTICATION_ERROR", data: res.data});
throw res.data;
}
})
}
};
我认为我应该以某种方式调用setState以便明确指示更改,或者在初始化组件时可能需要重新创建对后端的请求?
我将很高兴收到您的任何提示和帮助。预先谢谢你!
答案 0 :(得分:1)
您应按以下方式更改减速器ADD的大小写:
case 'ADD_NOTE':
return {
...state,
noteList:[action.note,...state.noteList]
}