当我使用setState时,我的组件没有重新渲染。我尝试在父组件和子组件上设置状态,但仍然不起作用。我还尝试了this.forceUpdate()..不工作..
下面是我的父组件:
import React, { Component } from "react";
import Header from "./Header";
import Note from "./Note";
class Notes extends Component {
constructor() {
super();
this.state = {
notes: [],
reRender: false
};
}
getUserId = () => {
var str = window.location.pathname;
var words = str.split("/");
return words[2];
};
handler = () => {
this.setState({
reRender: true
});
};
componentDidMount() {
fetch(`http://localhost:4000/notes?sls_id=${this.getUserId()}`)
.then(res => res.json())
.then(res => {
this.setState({
notes: res.data
});
});
}
render() {
const { notes } = this.state;
return (
<div>
<Header />
<ul style={{ marginTop: "10px", marginBottom: "10px" }}>
{Object.keys(notes).map(key => (
<Note
key={key}
index={key}
details={notes[key]}
action={this.handler}
/>
))}
</ul>
</div>
);
}
}
export default Notes;
下面是我的子组件:
import React, { Component } from "react";
import { Card, ListGroup, Button } from "react-bootstrap";
class Note extends Component {
deleteNote = _ => {
const prp = this.props.details;
fetch(`http://localhost:4000/notes/delete?note_id=${prp.note_id}`).catch(
err => console.error(err)
);
};
render() {
const prp = this.props.details;
return (
<Card style={{ margin: "15px" }}>
<Card.Header>
<div className="customerName">{prp.title}</div>
</Card.Header>
<Card.Body>
<blockquote className="blockquote mb-0">
<p>{prp.body}</p>
<footer className="blockquote-footer">
<cite title="Source Title">
posted on {prp.date.substring(0, prp.date.length - 14)}
</cite>
</footer>
</blockquote>
<button
style={{ margin: "15px", width: "150px" }}
type="button"
className="btn btn-danger"
onClick={() => {
this.deleteNote();
this.props.action();
}}
>
Delete note
</button>
</Card.Body>
</Card>
);
}
}
export default Note;
当我按下子组件上的按钮时,我想重新呈现我的组件...
发布于 2019-03-20 08:57:34
与其把this.props.action放在你的按钮里,不如试着把它扔到你的deleteNote里。
deleteNote = _ => {
this.props.action()
const prp = this.props.details;
fetch(`http://localhost:4000/notes/delete?note_id=${prp.note_id}`).catch(
err => console.error(err)
);
};
发布于 2019-03-20 10:41:22
所以我想我对我的问题无能为力,因为数据是从我的api中获取的。当我单击我的按钮时,它会发送一个删除MySql上特定行的请求。但我猜react不会重写我的数据..所以它实际上是在重新渲染..但是使用完全相同的数据..我决定设置一个方法来分割我的对象数组,这很好用:
updateNotes = key => {
var newArray = [];
var { notes } = this.state;
for (var i = 0; i < notes.length; i++)
if (notes[i].note_id !== key) newArray.push(notes[i]);
this.setState({
notes: newArray
});
};
https://stackoverflow.com/questions/55252000
复制相似问题