数据传输

#1

image
image
数据传输的时候.this上显示是有值的,但是this.props显示是空值。

如何解决API赋值后从一个页面传输到另一个页面
我是这样写的
但是现实的初始值

image
image

#2

console.log(123, this) 之所以能够看到是因为console的是 this的引用。
你的流程是

  1. Parent.componentWillMount
  2. Modal.componentDidMount
  3. Parent.compnentWillMount#setState(FetchUrl)
    你之所以在第二部的console.log(this) 能看到数据单纯是因为console的是this对象, 当你打开console点开this的内容的时候,程序已经执行到第三步了,
    如果你把 console.log(456, this.props) 改成 setTimeout(()=> console.log(456, this.props), 3000); 你也能看到。
    这里通常正确的做法是 componentWillReceiveProps来完成相关操作的,不过现在不推荐用这个生命周期,改成了getDerivedStateFromProps,
    你这里的话我觉得你只要改成下面这个, 确保 api返回数据之前不要生成Modal就行了
   return (<div>{t.state.fetchUrls && <Modal data={t.state.fetchUrls}/>}</div>)

最后推荐你用hooks来写

function Modal(props){
    const [details, setDetails] = React.useState(null)
    React.useEffect(()=> {
       if (!props.data) { return; }
       fetchDetails(props.data).then(setDetails)
    }, [props.data])
    if (!props.data) { return null; }
    return <div>{!details ? "Loading": JSON.stringify(details)}</div>
}
2 Likes