我是React钩子的新手。我正试图在一个小的警报中显示从另一个组件接收到的道具。
import React, { Fragment } from "react";
import { useAlert } from "react-alert";
const Alert = props => {
const alert = useAlert();
console.log("<< @ Alert props.message", props.message); // Diplays "deputy saved"
return (
<Fragment>
<button
className="btn btn-outline-secondary"
onClick={() => {
alert.show(props.message); // Displays the previous props received. Not the one from the console log above.
}}
>
Ajouter
</button>
</Fragment>
);
};
export default Alert;
此处是呈现警报的组件。该消息在被我的Api文件提取后被设置为setstate。此消息包含来自我的节点服务器的res.json。例如“代理创建”或“此代理已经存在”。然后,该消息通过属性发送到警报组件并作为道具接收。
// AddParty Component
import React from "react";
import { Form, Text, TextArea } from "informed";
import styled from "styled-components";
import Alert from "../../core/admin/Alert";
import "react-datepicker/dist/react-datepicker.css";
import Api from "../../../utils/Api";
class AddParty extends React.Component {
constructor(props) {
super(props);
this.state = {
image: {},
message: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange({ name, value }) {
this.setState({
[name]: value
});
}
async onSubmit(formState) {
console.info("formState", formState);
const { image } = this.state;
const newParty = new FormData();
newParty.append("image", image, image.name);
newParty.append("data", JSON.stringify(formState));
const message = await Api.addParty(newParty);
console.log("message :", message);
this.setState({
message
});
}
render() {
const { message, isSubmitted } = this.state;
console.log("message", message);
return (
<Container className="container">
<Form onSubmit={formState => this.onSubmit(formState)}>
<Label>
Nom du parti:
<Text
field="name"
type="text"
className="form-control form-control-sm"
/>
</Label>
<Label>
Description :
<TextArea
field="description"
className="form-control form-control-sm"
/>
</Label>
<Label>
Photo:
<input
type="file"
onChange={event =>
this.handleChange({
name: "image",
value: event.target.files[0]
})
}
/>
</Label>
<Alert
type="submit"
className="btn btn-outline-secondary"
message={message}
/>
</Form>
</Container>
);
}
}
export default AddParty;
我不明白为什么显示的警报始终是以前收到的道具中的警报,而不是控制台中显示的警报。
答案 0 :(得分:0)
当将prop
序列化为某个状态的属性的初始值时,事情可能会变得违反直觉。每当props
发生此更改时,React都不知道何时更新,因为状态从未更改。在这种情况下,您应该明确告诉React什么时候进行更新。这里需要shouldComponentUpdate
,以便您可以在新旧道具之间进行比较,并确定状态是否被更新
答案 1 :(得分:0)
我使用另一个名为react-toastify的react警报模块解决了我的问题。 https://www.npmjs.com/package/react-toastify 谢谢您对我的帮助