gpt4 book ai didi

javascript - render 方法中的 react map() 函数晚了一步

转载 作者:行者123 更新时间:2023-11-30 21:12:51 24 4
gpt4 key购买 nike

有件事我无法理解,为什么当我将 props 传递给一个组件,然后对它们执行 map() 后,它又出现了 1 个项目?这是代码:

class ImageInput extends Component {
constructor(props){
super(props);
this.state = {
photos: props.photos
}
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.inputElement.click();
}


render(){
const previews = this.state.photos.map((photo, index) =>
<ImagePreview key={index} preview={photo.preview} name={photo.name} />
);
console.log(1, this.state.photos);
console.log(2, previews);
return(
<div className="form-image-field">
<div className="form-image-input" onClick={this.handleClick}>
<p className="image-input-title">Add photo</p>
<p className="image-input-text">Minimum size of 300x300 jpeg jpg png 5 MB</p>
<input type="file"
accept="image/*"
style={{"display":"none"}}
ref={input => this.inputElement = input}
onChange={this.props.handleImage} />
</div>
{ previews }
</div>
);

}

添加第一张图片后 console.log 看起来像:

   1 []0: {file: File, preview: "...", name: "C..."}
length: 1
2 []
length: 0

第二个之后是:

1 [{…}]0: {file: File, preview: "...", name: "..."}
1: {file: File, preview: "...", name: "..."}
length: 2
2 [{…}]0: {...SomeObject...}
length: 1

最佳答案

因为你是通过引用来做的 - 大概是在父组件中插入 props.photos - 而你的 child 在 this.state.photos 中有它 - 但你渲染它来自状态,而不是 Prop 。所以更新不会被拾取/注意到,直到以后发生变化。

要么通过 componentWillReceiveProps(newProps){ this.setState({photos: newProps.photos}) } 保持同步,要么只是循环 this.props.photos拥有本地状态并保持无状态。

关于javascript - render 方法中的 react map() 函数晚了一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com