将状态从父函数组件传递给子类组件

时间:2021-04-15 07:45:28

标签: reactjs react-native

嗨,我正在尝试将值从父级传递给子级,以便每当父级状态更改时,子级都会获取该值并重新呈现视图。但是使用下面的代码,该值仅从父级移动到子级一次,然后无限期挂起。

这是父函数组件

export default function App() {  
 const [link, setLink ] = useState("");

 useEffect(() => {
    responseListener.current = 
    Notifications.addNotificationResponseReceivedListener(response => {
    let pushLink = JSON.stringify(response.notification.request.content.data.url)
    setLink(pushLink);
  }
}, []);
}

// Send to child class component
const androidPlatform = <AndBrowser link = {link} />;
 <View style={styles.browser}>
            {Platform.OS === 'ios'? iOSPlatform : androidPlatform}
 </View>

然后是子类组件

class AndBrowser extends Component {
  // PUSH_URL LINK
  //--------------------------------------
    constructor(props) {
     
        super(props);
        this.state = {
          viewLink : this.props.link,
        }
      //   console.log('test------'+this.props.link);
    }
  //--------------------------------------
 render() {
    if(this.props.link!=undefined){
       linked_url = encodeURI(this.props.link);
    }
 return ( 
      <WebView
        source={{ uri :linked_url }}/>
 );

不知道如何进行这项工作。

1 个答案:

答案 0 :(得分:0)

当您尝试使用无状态时,它将重新呈现,如下所示

class AndBrowser extends Component {
   render() {
    return <WebView source={{ uri: this.props.link }} />;
  }
}

您也可以尝试通过将状态从父级重置为子级来重新渲染它。