在我的项目中,当使用循环通过数据文件时。map()
函数,我正在将一个函数(updatestate
)从父组件App
传递给子组件Main
,该子组件允许子组件调用。setState()
并附加到父状态的数组中。
但是,当我调用此函数来设置父级的状态时,映射的部分--{contents}
--将不会重新加载,除非我再次点击屏幕。
有什么想法吗?我是否缺少一些绑定或需要执行一些组件安装或其他操作?我尝试添加这个。forceUpdate()
在eventHandler中,但是**映射的{contents}
部分**仍然不会自动呈现。
const RootStack = StackNavigator(
{
Main: {
screen: Main}
}
);
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
favoritesList: []
};
}
updateArr=(itemname, url)=>{this.setState({ favoritesList: [...this.state.favoritesList, {"item_name":itemname, "url":url}]})};
render() {
return <RootStack screenProps={{appstate: this.state,
updatestate: this.updateArr}}
/>;
}
}
class Main extends React.Component {
render() {
var updatestate = this.props.screenProps.updatestate;
//collection is the data (local JSON) i'm looping thru via .map in Main Component
const contents = collection.map((item, index) => {
return (
<Card key={index}
onSwipedRight={() => {updatestate(item.item_name,item.url)}}
>
<View> //THIS and anything after <Card> doesn't render for the next card automatically if I do 'onSwipedRight'
<Image
source={{uri: item.url}} />
</View>
</Card>
)
},this);
return (
<View>
<CardStack>
{contents} //THIS IS THE PART THAT WON'T AUTO-RERENDER AFTER THE EVENT HANDLER THAT SETS THE PARENT'S STATE
</CardStack>
</View>
);
}
}
为了确保这不是事件处理程序的问题,我添加了一个不设置父级状态的函数,并且具有
class Main extends React.Component {
render() {
var updatestate = this.props.screenProps.updatestate;
var newfunc = (a, b) => {console.log('a:', a, 'b:', b)};
const contents = collection.map((item, index) => {
return (
<Card key={index}
newfunc(item.item_name,item.item_name);}}
// onSwipedRight={() => {updatestate(item.item_name,item.url); }}
>
试着像这样重写你的设置状态
import { InteractionManager } from "react-native";
updateArr = (itemname, url) => {
InteractionManager.runAfterInteractions(() => {
this.setState( prevState => ({
favoritesList: [...prevState.favoritesList, { "item_name":itemname, "url":url } ]
});
});
}
// add this line to your parent component constructor()
this.updateArr = this.updateArr.bind(this);
尝试不使用index
作为key
。有意义的键值有助于引擎找出需要重绘的内容。
在您的情况下,我建议首先使用key={item.url}
。
https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-mod-e0349aece318