3 回答

TA貢獻(xiàn)1860條經(jīng)驗 獲得超8個贊
要在屏幕上呈現(xiàn)通知,通常我會使用 React Portals
為此,您的 Notification 組件需要通過 Portal 渲染到 DOM
const notificationRoot = document.getElementById('notification-root'); // Create the element in your main html file in order for your notification to "portal" in
const Notification = (props) => {
return (
<div>
<div>
<p>props.text</p>
</div>
</div>
);
};
const DisplayNotification = () => {
const domNode = usememo(() => document.createElement('div'), []);
useEffect(() => {
notificationRoot.appendChild(domNode);
return () => {
notificationRoot.removeChild(domNode);
}
}, [])
return ReactDOM.createPortal(
<Notification />,
domNode
); // Portal to your node
}
通過渲染DisplayNotification,您Notification應(yīng)該會彈出。

TA貢獻(xiàn)1786條經(jīng)驗 獲得超13個贊
在您的axios.then中,您可以將結(jié)果存儲在狀態(tài)中,并設(shè)置超時以在 1 秒后清除狀態(tài)。然后,如果狀態(tài)中有某些東西,則呈現(xiàn)通知
const Index = (props) => {
const [text, setText] = useState();
let getData = () => {
axios.get('url')
.then(function (response) {
setText(response.data);
setTimeout(() => setText(), 1000);
})
.catch(function (error) {
console.log(error);
});
}
return (
<>
<button onClick={() => getData()}>Get data</button>
{text &&
<Notification text={text} />
}
</>
);
}

TA貢獻(xiàn)1874條經(jīng)驗 獲得超12個贊
您應(yīng)該使用 redux 來實(shí)現(xiàn)這一點(diǎn),當(dāng)您從 API 接收數(shù)據(jù)時,調(diào)度一個返回 true/false 布爾值的 redux 操作。
這個提案解決方案的好處是,在您開發(fā)系統(tǒng)后,您只需調(diào)用一個函數(shù),然后將其發(fā)送到您的商店就可以了!!
將您<Notification />的組件放在應(yīng)用程序的頂部
喜歡 :
const App = (props) => {
return (
<Provider store={store}>
<Notification />
<BrowserRouter>
<Route exact path="/" render={/* YOUR HOMEPAGE COMPONENT */} />
</BrowserRouter>
</Provider>
);
}
請在此處查看 redux 解決方案:https ://redux.js.org/introduction/getting-started
在你的里面<Notification />
不要忘記在 redux 上連接你應(yīng)該使用的connect()是 HOC(高階組件)
import React from 'react';
import { connect } from 'redux'
const Notification = (props) => {
return (
<div>
<div>
<p>props.text</p>
</div>
</div>
);
//and delete after 1 second
}
const mapStateToProps = (state) => {
/* Get your state from your store notification for example */
return {}
}
export default connect(mapStateToProps)(Notification);
添加回答
舉報