我是React.js的初学者,并试图理解道具的概念。有多个记录的州。
我有两个组件 -
在UserData.jsx中,我使用this.state作为用户记录。我希望通过子组件UserDataResult.jsx显示此记录。
不知道我做错了什么,所以我在控制台日志中遇到错误。
错误是:未捕获RangeError:超出最大调用堆栈大小
代码:
** UserData.jsx **
import React from "react";
import UserDataResult from "./UserDataResult.jsx";
class UserData extends React.Component{
constructor (props){
super(props);
this.state = {
users : [
{
id : 1,
name : "Jack",
age : 32,
location : "USA",
skill : "Drummer",
},
{
id : 2,
name : "Andrew",
age : 35,
location : "USA",
skill : "Guitar player",
},
]
};
}
render(){
return(
<section>
<h6> Headline </h6>
<hr />
<div>
{
this.state.users.map( (contact) => {
return <UserDataResult contact={contact} />
} )
}
</div>
</section>
);
}
}
export default UserData;
** UserDataResult.jsx **
import React from "react";
class UserDataResult extends React.Component{
render(){
return(
<section>
<div>
<p>
{this.props.contact.id}
{this.props.contact.name}
{this.props.contact.age}
{this.props.contact.location}
{this.props.contact.skill}
</p>
</div>
</section>
);
}
}
export default UserDataResult;
答案 0 :(得分:0)
试试这个构造函数:
您需要包含道具以允许React将道具正确地传递到组件中。我不记得确切的原因。
constructor(props) { // you need to include props
super(props); // you need to include it here also
this.state = {
users = [
{
id : 1,
name : "Jack",
age : 32,
location : "USA",
skill : "Drummer"
},
{
id : 2,
name : "Andrew",
age : 35,
location : "USA",
skill : "Guitar player"
}
]
};
}
以上内容可让您访问this.state.users
这是一个数组。
然后,在您的组件中尝试此操作:
<div>
<UserDataResult checkResult={this.state.users} />
</div>
然后,您可以通过推入阵列来更新它。
尝试制作一些允许你调用它的东西:
const newUsersArray = this.state.users.push({
id: 3
name: 'Bob Ross'
age: 25
location: 'Cambodia'
skill: 'Maximum'
})
this.setState({ users: newUsersArray })
你需要将状态视为24/7不可变。始终用更新的值替换它。
React在幕后进行各种花哨的比较,帮助您优化性能。注意我是如何将新用户添加到数组中然后重新分配的。
这将为您提供Redux世界,我们使用Reducer并直接操纵状态是100%非法。
现在开始考虑做this.state.push()
或state.users.bob = 'ok'
是不好的。你想做我上面展示的,鲍勃的例子就像:
return {
...state,
bob: 'ok'
}
它的作用是创建一个新对象并将现有状态“扩散”到它中,所以它就像当时一样,然后它只是将bob: 'ok'
作为属性添加到该新对象上它出现在/之后,它优先并覆盖名为bob
的现有密钥。
这有点高级,但你应该知道减速器努力成为pure functions
并且使用React不可变的非常重要。做一些阅读。
这些东西与组件re-render
的位置,时间和原因有关。它是React炙手可热的表现的核心。
如果您从渲染功能或生命周期方法中调用this.setState()
,它可能会进入无限循环,因为setState触发了渲染组件,重新渲染再次触发setState。