在我的项目中,在使用函数循环数据文件时.map()
,我将一个函数 ( updatestate
) 从父组件App
传递给子组件Main
,它允许子组件调用.setState()
并附加到父状态的数组。
但是,当我调用这个函数来设置 Parent 的状态时,除非我再次点击屏幕,否则映射的部分- {contents}
-不会重新呈现。
有任何想法吗?我是否缺少一些绑定或需要做一些 componentDidMount 或任何事情?我尝试this.forceUpdate()
在 eventHandler 中添加,但 **mapped{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>
);
}
}
为了确保事件处理程序没有问题,我添加了一个不设置父级状态的函数,并<Card>
在事件处理程序上调用它——它运行良好,子组件<Card>
完美呈现。似乎是updatestate
从父级传递给子级的函数在上游调用,由于某种原因导致子级在事件处理程序之后.setState()
无法渲染/未完成映射映射。{contents}
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); }}
>