【发布时间】:2021-04-30 02:04:16
【问题描述】:
我正在尝试在我的应用程序中创建一个删除功能,该功能似乎可以从后端删除对象,但不是在前端。
这是我的项目结构:
在actions/deleteJournal.js中
export const deleteJournal = (journal) => {
return dispatch => {
fetch(`http://localhost:3001/journals/${journal.id}` , {
method: "DELETE" })
.then(resp => resp.json())
.then(journal => { dispatch({ type: "DELETE_JOURNAL", journal })
})
}
}
在 reducers/journalsReducer.js 中
const initialState = {
journals: [],
loading: true
}
const journalsReducer = (state=initialState, action) => {
switch(action.type) {
case "LOADING":
return {
...state,
loading: true
}
case "SET_JOURNALS":
return {
...state,
loading: false,
journals: action.journals
}
case "ADD_JOURNAL":
return {
...state,
journals: [...state.journals, action.journal],
}
case 'DELETE_JOURNAL':
return {
journals: state.journals.filter(todo => todo.id !== action.id),
...state
}
default:
return state;
}
}
export default journalsReducer
在 components/List.js 中
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Journal from './Journal'
import { deleteJournal } from '../actions/getJournals'
class ListFiltered extends Component {
render() {
const journals = this.props.journals.map( journal => journal.locationId === this.props.locationId && <Journal key={journal.id} title={journal.title} content={journal.content} id={journal.id} deleteJournal={this.props.deleteJournal} />)
return (
<div>
{journals}
<p></p>
</div>
)
}
}
const mapStateToProps = state => {
return {
journals: state.journals
}
}
export default connect(mapStateToProps, {deleteJournal})(ListFiltered)
在 components/Journal.js 中
class Journal extends Component {
render() {
const { id, title, content } = this.props;
return (
<div>
<ul>
<li>
<h3>{ title } </h3>
<p> { content }</p> <button onClick={() => this.props.deleteJournal(this.props) }>Delete</button>
</li>
</ul>
</div>
)
}
}
export default Journal
所以这似乎给了我一个错误 " Uncaught (in promise) SyntaxError: Unexpected end of JSON input 在 deleteJournal.js:48" 我检查了我的服务器,它似乎正在从那里删除它,但前端没有任何内容,当我刷新该项目时,它被删除了。
我该怎么做才能自动从前端删除项目?
【问题讨论】:
标签: ruby-on-rails reactjs redux