Reactjs 如何更新组件列表中组件的道具
我正在尝试更新组件列表中组件的属性值。下面是一个例子 我正在用ReactNative开发一个应用程序Reactjs 如何更新组件列表中组件的道具,reactjs,react-native,Reactjs,React Native,我正在尝试更新组件列表中组件的属性值。下面是一个例子 我正在用ReactNative开发一个应用程序 。。。 建造师(道具){ 状态={ 组件:[*组件列表*], } componentDidMount(){ fetchingAPI()。然后(响应=>{ 常量组件=[]; for(response.data的常量数据){ 组件。push(); } this.setState({components}); }); } render(){ 返回( ... {this.state.components
。。。
建造师(道具){
状态={
组件:[*组件列表*],
}
componentDidMount(){
fetchingAPI()。然后(响应=>{
常量组件=[];
for(response.data的常量数据){
组件。push();
}
this.setState({components});
});
}
render(){
返回(
...
{this.state.components}
...
);
}
当我想更新组件时,我会更新整个状态命名组件,如:
updateComponent(索引,newNumOfLike){
常量组件=this.state.components;
组件[索引]=
this.setState({components});
}
但是,此方法更改组件,而不是更新。对吗?我的意思是components
状态已更新,但components[index]
中的MyComponent
已更改
那么,如果我想用更新道具numfolike
的方式直接更新components[index]
中的MyComponent
,我该怎么做呢
添加:
我没有提到的是,MyComponent
中有一个Image
标记。因此,如果我使用FlatList
或array.prototype.map
,会有几个问题
Image
标记,因此如果我更新列表项,整个Image
标记将在列表项重新呈现后闪烁您可以使用中介绍的
setNativeProps
组件[index].setNativeProps(propsObj)
您可以这样修改您的组件didmount
函数(这样代码中就不会出现争用或异步条件)——:
componentDidMount(){
fetchingAPI()。然后(响应=>{
这是我的国家({
组件:this.state.components.concat(
response.data.map(i=>)
)});
});
}
你能试试平面列表吗
例如:
为什么不使用FlatList
。我建议使用只在state
中存储响应数据。然后在render
方法中,您可以根据数据填充视图。只将数据保存在state中,然后使用map函数渲染它们会更容易谢谢您的回答。我有一个问题。实际上,MyComponent
有一个图像
标记。因此这里有两个问题。1.当我更新状态时,整个列表项都会更新。因此,如果有很多项,更新速度会非常慢。2.由于更新状态将更新整个平面列表项,因此图像
标记在更新后会闪烁。是否有方法更新某个组件t?你能在渲染项中使用纯组件吗?谢谢你的回答。但是我可以使用MyComponent
上的setNativeProps
方法,而MyComponent
没有这样的方法。我如何使用它?你有关于它的例子吗?
componentDidMount() {
fetchingAPI().then(response => {
this.setState({
components: this.state.components.concat(
response.data.map(i => <MyComponent numOfLike={i.numOfLike} />)
)});
});
}
...
constructor(props) {
state = {
componentsData: [],
}
componentDidMount() {
fetchingAPI().then(response => {
this.setState({componentsData: response.data});
});
}
_renderItems = ({ item, index }) => {
return(
<MyComponent numOfLike={item. numOfLike} />
)
}
render() {
return (
...
<FlatList
data={this.state.componentsData}
renderItem={this._renderItems}
keyExtractor={(item, index) => index.toString()}
extraData={this.state}
/>
...
);
}
updateAComponent(index, newNumOfLike) {
const data = this.state.componentsData;
data[index].numOfLike = newNumOfLike
this.setState({componentsData: data});
}