当我设置状态时,我的组件没有重新渲染。我试图在父组件和子组件上都设置状态,但仍然无法正常工作。我也尝试过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;
当我在子组件上按下按钮时,我想重新渲染组件...
答案 0 :(得分:0)
与其在按钮中放置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)
);
};
答案 1 :(得分:0)
所以我想我不能做太多事情,因为数据是从我的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
});
};