【发布时间】:2018-08-05 09:28:16
【问题描述】:
在我的项目中,在使用 .map() 函数循环遍历数据文件时,我将一个函数 (updatestate) 从父组件 App 传递给子组件 Main,它允许Child 调用 .setState() 并在 Parent 状态下追加到数组。
但是,当我调用这个函数来设置 Parent 的状态时,映射部分 -- {contents} -- 除非我点击再次屏幕。
有什么想法吗?我是否缺少一些绑定或需要做一些 componentDidMount 或任何事情?我尝试在 eventHandler 中添加this.forceUpdate(),但**映射的{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); }}
>
【问题讨论】:
标签: javascript reactjs react-native react-component