我试图在组件更新后从服务器获取数据,但我无法做到这一点.据我所知componentWillUnmount,当组件即将被销毁时被调用,但我永远不需要销毁它因此对我来说没用.这会是什么解决方案?什么时候我应该设置状态?
async componentDidUpdate(prevProps, prevState) {
if (this.props.subject.length && prevProps.subject !== this.props.subject) {
let result = await this.getGrades({
student: this.props.id,
subject: this.props.subject
});
this.setState({
subject: this.props.subject,
grades: result
});
}
}
async getGrades(params) {
let response, body;
if (params['subject'].length) {
response = await fetch(apiRequestString.gradesBySubject(params));
body = await response.json();
} else {
response = await fetch(apiRequestString.grades(params));
body = await response.json();
}
if (response.status !== 200) throw Error(body.message);
return body;
}
Run Code Online (Sandbox Code Playgroud)
完整错误:
Warning: Can't call setState (or forceUpdate) on an unmounted …Run Code Online (Sandbox Code Playgroud) 如何能在useEffect钩(或任何其他挂钩的这个问题)可以被用来复制componentWillUnmount?
在传统的类组件中,我将执行以下操作:
class Effect extends React.PureComponent {
componentDidMount() { console.log("MOUNT", this.props); }
componentWillUnmount() { console.log("UNMOUNT", this.props); }
render() { return null; }
}
Run Code Online (Sandbox Code Playgroud)
随着useEffect钩:
function Effect(props) {
React.useEffect(() => {
console.log("MOUNT", props);
return () => console.log("UNMOUNT", props)
}, []);
return null;
}
Run Code Online (Sandbox Code Playgroud)
(完整示例:https : //codesandbox.io/s/2oo7zqzx1n)
这是行不通的,因为返回的“清理”功能会useEffect捕获安装过程中的道具,而不会在卸载过程中捕获道具的状态。
我怎么能获得最新版本的道具的useEffect清理,而不在每一个道具的变化运行的函数体(或清理)?
一个类似的问题没有解决获得最新道具的问题。
该反应文档状态:
如果要运行效果并仅将其清除一次(在挂载和卸载时),则可以传递一个空数组([])作为第二个参数。这告诉React您的效果不依赖于props或state的任何值,因此它不需要重新运行。
但是在这种情况下,我依赖道具...但仅用于清理部分...
是否存在 componentDidUpdate 不会触发的情况,即使在 React 中更新了 props?
我正在尝试将道具从父组件传递到子组件,即使它被调用了两次(不知道为什么,componentDidMount应该只被调用一次),道具似乎还是空的。
父组件:
class Members extends Component{
constructor(props){
super(props);
this.state = {
interests: []
}
}
componentDidMount(){
fetch(interestUrl, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Authorization": this.props.authToken
}
})
.then((response) => response.json())
.then((json) => {this.setState({interests: json})})
.catch(error => {console.log("Error: " + error)})
};
render(){
return(
<div className="Members-body">
<div className="Menu-sidebar">
<Menu interestList = {this.state.interests}/>
</div>
<div className="Main-container">
<Main/>
</div>
</div>
)
}
}
export default Members;
Run Code Online (Sandbox Code Playgroud)
子组件:
class Menu extends Component {
constructor(props){
super(props);
}
componentDidMount(){
console.log("interestList: " + this.props.interestList); …Run Code Online (Sandbox Code Playgroud) 我正在使用 react js 和 node js api 实现一个简单的用户身份验证系统。这就是我在ComponentWillMount方法中所做的:-
1.检查令牌是否存在(在localStorage中)
2.如果它不存在,那么状态“令牌”的值将保持空白
3.如果它存在,则使用对后端的请求检查它是否有效。
4.如果令牌有效,则状态“令牌”为localstorage.token
5.如果令牌无效,则状态“令牌”的值将保持空白
在渲染方法中,我根据状态“令牌”的值添加了条件渲染,即如果状态“令牌”为空白,则将呈现正常页面,否则将被重定向到用户页面。
问题是我可以使用任何 React 开发人员工具更改状态“令牌”的值。这导致了使用假令牌登录的漏洞。为了避免每次使用componentDidUpdate shouldComponentUpdate等生命周期方法更改状态“令牌”时,我都必须检查它的有效性。但是正如官方文档中提到的
reactshouldComponentUpdate只作为性能优化存在。不要依赖它来“阻止”渲染,因为这可能会导致错误。
使用componentDidUpdate没有用,因为它会在组件因状态改变而改变后被调用。
使用componentWillUpdate在官方文档中被称为 Unsafe
我不知道如何解决这个漏洞。这是组件的代码
import React,{Component} from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';
import Home from './Home';
import Nav from './Nav';
import Login from './Login';
import Signup from './Signup';
class Out extends Component{
constructor(){
super();
this.state = {
token : '',
isLoading:false
}
this.isLoading …Run Code Online (Sandbox Code Playgroud) javascript authentication authorization reactjs react-lifecycle
背景
我正在使用一个使用ReactJS作为渲染库的Meteor应用程序.
目前,我在更新数据时重新渲染子组件时遇到问题,即使父级正在访问更新的数据并且据称将其传递给子级.
Parent组件是一个数据表.子组件是单击编辑日期字段.
它(理论上)的工作方式:父组件将日期的现有数据作为prop传递给子组件.子组件获取现有的道具数据,处理它并使用它设置一些状态,然后有2个选项:
我在表中每行使用子组件两次,每次使用它时,它需要访问数据库中的最新日期数据.因此,如果数据在一个字段中更改,则第二个字段应反映该更改.
问题
除非我手动刷新页面并强制子组件使用新数据进行渲染,否则第二个字段不会反映数据库中的更改.编辑的字段是反映数据的变化,因为它反映了什么是存储在状态.
阅读完React文档之后,我确定问题是因为日期是作为一个prop进入,然后作为一个状态处理 - 并且因为该组件不会从prop更改中重新呈现.
我的问题
我该怎么做才能解决这个问题?
我对文档所做的所有阅读强烈建议远离诸如forceUpdate()和getDerivedStateFromProps()之类的东西,但结果我不确定如何通过我想要的方式传递数据.
思考?
我的守则
我已经将代码缩减了一点并删除了特定于我的项目的变量名称,但是如果它有帮助我可以提供更多的实际代码.我认为我的问题比直接调试更具概念性.
亲
ParentComponent () {
//Date comes as a prop from database subscription
var date1 = this.props.dates.date1
var date2 = this.props.dates.date2
return(
<ChildComponent
id='handle-date-1'
selected={[date1, date2]} />
<ChildComponent
id='handle-date-2'
selected={[date1, date2]} />
)
}
Run Code Online (Sandbox Code Playgroud)
儿童
ChildComponent() {
constructor(props) {
super(props);
this.state = {
date1: this.props.selected[0],
date2: this.props.selected[1],
field: false,
};
}
handleDatePick() {
//Handles the …Run Code Online (Sandbox Code Playgroud) 我正在开发一个反应应用程序,我想根据某些条件阻止我的组件卸载。
据我研究,我发现使用 React Router 的 setRouteLeaveHook 的一个选项(如此处所述)。但问题是我有相同的路线,即两个组件的 url 相同。另外,我没有 this.props.router 选项或 this.context.router 选项,我可以在其中传递它。
有什么我可以做的吗?
它说 componentWillReceiveProps 已被重命名...但我的代码中没有“componentWillReceiveProps”只有效果...也许它在节点模块中。
所以我试图忽略他们,但我不知道如何......
我使用了 create-react-app 并且我正在使用 ts-lint。
如果我想在第一次渲染组件后调用 API,我知道我们有useEffect钩子来调用 API 方法。(我只讨论功能组件。没有类组件)。
有什么办法,我可以在我的组件第一次渲染之前调用 API。
这个问题的原因是,如果某些 UI 部分依赖于 API,我不想在第一次渲染时向用户显示任何不完整的信息,一旦我从 API 获取数据,这些信息就会改变。这似乎是一个糟糕的 UI 体验。
编辑:我得到了一些使用 useLayoutEffect 或任何消耗性标志来检查它是否渲染的建议。我已经检查过 useLayoutEffect 不起作用,并且通过使用 consumable 标志,我们只是增加了复杂性。
对此我们有没有更好的办法呢?
javascript reactjs react-lifecycle react-hooks react-functional-component
我刚刚开始学习React。
在学习 LifeCycle 时,我想知道componentDidUpdate方法。
据我所知,componentDidUpdate方法可以有三个参数(prevProps, prevState, snapshot)。prevState如果我能从中找出componentDidUpdate是snapshot为了什么?
这可能不重要,但我只是很好奇
react-lifecycle ×10
reactjs ×10
javascript ×5
react-hooks ×2
react-props ×2
meteor ×1
react-router ×1