什么会在视图中刷新视图,或者代码是否始终显示?
我有一个名为removeAdmin和makeAdmin的函数,用于添加和删除用户作为管理员,然后当用户是管理员时,呈现成员组件呈现和管理员盾徽标。它运行正常,但我想知道每次使用函数更改UI时是否触发渲染,或者渲染是否正在实时监听其组件的变化?
class MemberList extends Component {
constructor(props) {
super(props)
this.state = {
members: [],
loading: false,
administrators: []
}
this.makeAdmin = this.makeAdmin.bind(this)
this.removeAdmin = this.removeAdmin.bind(this)
}
componentDidMount(){
this.setState({loading:true})
fetch('https://api.randomuser.me/?nat=US&results=12')
.then(response => response.json())
.then(json => json.results)
.then(members => this.setState({
members,
loading:false
}))
}
makeAdmin(email){
const administrators = [
...this.state.administrators,
email
]
this.setState({administrators})
}
removeAdmin(email){
const administrators = this.state.administrators.filter(
adminEmail => adminEmail !== email
)
this.setState({administrators})
}
render() {
const { members, loading } = this.state
return (
<div className="member-list">
<h1>Society Members</h1>
{
(loading) ?
<span> loading...</span>:
<span>{members.length} members</span>
}
{ (members.length)?
members.map(
(member, i) =>
<Member key={i}
// This admin prop is worked out by enumerating through the administrator
// array with some(). some() passes in the enumerators, checking whether
// the current member in members.map() exists in the administrators array
// and returns admin=true if so.
admin={this.state.administrators.some(
adminEmail => adminEmail === member.email
)}
name={member.name.first + '' + member.name.last}
email={member.email}
thumbnail={member.picture.thumbnail}
makeAdmin={this.makeAdmin}
removeAdmin={this.removeAdmin}/>
):
<span>Currently 0 members</span>
}
</div>
)
和会员组成部分:
class Member extends Component {
componentWillMount(){
this.style={
backgroundColor: 'grey'
}
}
render() {
const { name, thumbnail, email, admin, makeAdmin, removeAdmin } = this.props
return (
<div className="member" style={this.style}>
<h1>{ name } {(admin) ? <FaShield/> : null}</h1>
<div>
<img src={ thumbnail }/>
</div>
<div>
{
(admin)?
<Button title="Make Admin" onClick={() => removeAdmin(email) } color="#841584"> Remove Admin </Button>
:
<Button title="Make Admin" onClick={ () => makeAdmin(email) } color="#841584"> Make Admin </Button>
}
<a href={`mailto:${ email }`}><p> {email} </p></a>
</div>
</div>
)
}
}
export default Member
答案 0 :(得分:2)
触发组件上新渲染的内容是状态更改或接收新属性时。
有两个主要对象驱动每个组件中的渲染,this.props
和this.state
。如果任何此对象得到更新,则会执行render
方法。
每当您向儿童发送新属性时,this.props
对象都会更新。使用this.state
方法更新this.setState
。
话虽如此,跟踪发送给孩子的属性非常重要,根据经验,我总是建议不要使用spread操作员将道具传递给孩子,例如:
<Parent>
<Child {...this.props} />
</Parent>
我会避免那种模式,因为如果任何道具发生变化,那么所有道具都会被发送给孩子。相反,我建议只发送孩子们需要的东西。
<Parent>
<Child some={this.props.value} />
</Parent>
当需要渲染组件时,你需要非常小心,否则很容易重新渲染所有内容!这将导致性能问题。