简体   繁体   English

子组件未使用新道具进行更新

[英]Child Component Isn't Updating with New Props

I'm having an issue getting my child component to update with new props. 我在让子组件更新新道具时遇到问题。 I'm deleting an item from the global state and it's successful. 我正在从全局状态中删除一个项目,并且成功。 But when the item gets deleted, I'm expecting that item to no longer show. 但是,当该项目被删除时,我希望该项目不再显示。 It's still being shown but if I were to move to another screen then back, it's gone. 它仍在显示,但是如果我要移到另一个屏幕然后返回,它就消失了。 Any idea on what I might be missing here? 我可能在这里想念的任何想法吗?

Thanks!! 谢谢!!

export default class Summary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      pickupData: this.props.pickup
    };
  }

  handleDelete(item) {
    this.props.deleteLocationItem(item);
  }

  render() {
    const pickup = this.state.pickup;

    return (
      <View>
        {pickup.map((item, i) => (
          <LocationItem
            name={item}
            onPressDelete={() => this.handleDelete(item)}
          />
        ))}
      </View>
    );
  }
}

const LocationItem = ({ onPressDelete, name }) => (
  <TouchableOpacity onPress={onPressDelete}>
    <Text>Hi, {name}, CLICK ME TO DELETE</Text>
  </TouchableOpacity>
);

------- Additional Info ------ - - - - 附加信息 - - -

case 'DELETE_LOCATION_INFO':
  return Object.assign({}, state, {
  pickup: state.pickup.filter(item => item !== action.action)
})

export function deleteLocationInfo(x){
  return {
    type: DELETE_LOCATION_INFO,
    action: x
  }
}

Your deleteLocationItem must be something like this: 您的deleteLocationItem必须是这样的:

deleteLocationItem(id) {
  this.setState({
   items: this.state.items.filter(item => item.id !== id)
  });
}

Then inside your Summary class you dont need to set the prop again. 然后,在您的Summary类中,您无需再次设置道具。 Just receive pickup from props like this: 只需从道具中接收即可,如下所示:

render (

const { pickup } = this.props;
return(
  <View>
    { pickup.map
...

Render is happening based on the state which is not updated other than in constructor. 渲染是根据除构造函数以外未更新的状态发生的。 When the prop updates from parent, it is not reflected in the state. 当prop从父对象更新时,它不会反映在状态中。 Add componentWillReceiveProps method to receive new props and update state, which will cause new data to render 添加componentWillReceiveProps方法以接收新道具并更新状态,这将导致呈现新数据

But more preferably, if the state is not being changed in any way after initialization, render directly using the prop itself which will resolve this issue 但更可取的是,如果初始化后状态没有以任何方式更改,请直接使用prop本身进行渲染,这将解决此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM