在构造函数中分配的道具在componentDidMount

时间:2019-04-09 06:57:09

标签: react-native

有一个组件Chat定义如下:

constructor(props) {
      super(props);

      this.props = {
        eventId : props.navigation.state.params.eventId,
        user: props.navigation.state.params.user
      }
      console.log("user in chat  : ", this.props.user);
      console.log("event id in chat: ", this.props.eventId);
      this.state = {
        messages: []
      };
    };

    async componentDidMount() {
      try {
        let url = `http://192.168.2.133:3000/api/messages/e?_device_id=${encodeURIComponent(DeviceInfo.getUniqueID())}&event_id=${encodeURIComponent(this.props.eventId)}`;
        console.log("message URL : ", encodeURIComponent(url));
        let res = await fetch(encodeURIComponent(url), {
          method: "GET",
           headers: {
            "x-auth-token": "mytoken", 
          }
        });

这是我的控制台输出:

'event id in chat: ', 1
04-08 23:42:24.456 15213 15259 E ReactNativeJS: 'Warning: %s(...): When calling super() in `%s`, make sure to pass up the same props that your component\'s constructor was passed.', 'Chat', 'Chat'
04-08 23:42:25.085 15213 15259 I ReactNativeJS: 'message URL : ', 'http%3A%2F%2F192.168.2.133%3A3000%2Fapi%2Fmessages%2Fe%3F_device_id%3D02f7e7aa907a2a2b%26event_id%3Dundefined'

event id中有Chat constructor等于1。但是,由event_id分配的this.props.eventIdundefined中是componentDidMount。我不知道为什么this.props.eventId不返回构造函数中的1。

以下是父组件中的_onPress函数,它带有2个道具:

_onPress(id) {
      this.props.navigation.navigate("Chat", {eventId: id, user: this.state.user});
    }

2 个答案:

答案 0 :(得分:1)

道具是不可变的,您不能在组件内部更改它们。改用默认道具。

答案 1 :(得分:1)

您无法在子组件中编辑子道具, 我建议在状态下使用它们,并且在componentDidMount()中可以检查并更新它是否发生变化