我想创建一个实际上来自某些异步服务(例如服务器数据)的上下文。
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:Transmission="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Transmission:ShipFromLocationRef/LocationRef/LocationGid/Gid/Xid">
<xsl:copy>
<xsl:apply-templates select="@*|../Transmission:ShipToLocationRef/LocationRef/LocationGid/Gid/Xid/text()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Transmission:ShipToLocationRef/LocationRef/LocationGid/Gid/Xid">
<xsl:copy>
<xsl:apply-templates select="@*|../Transmission:ShipFromLocationRef/LocationRef/LocationGid/Gid/Xid/text()"/>
</xsl:copy>
</xsl:template>
https://stackblitz.com/edit/react-ts-8zzbxa?file=index.tsx
期望值为://the async service to bring the context data
export const fetchContextFromAsycnService = () => {
return new Promise(resolve => setTimeout(
() => resolve('Hey, im in the async context and I am the correct value'), 200)
);
}
class App extends Component {
render() {
let value = 'Im not the correct value';
fetchContextFromAsycnService().then(x => value = x as string);
return (
<AsyncContext.Provider value={value}>
<SomeComponent />
</AsyncContext.Provider>
);
}
}
//user the value
export const SomeComponent = ( ) => {
return (
<AsyncContext.Consumer>
{value => <div>{value}</div>}
</AsyncContext.Consumer>)
}
render(<App />, document.getElementById('root'));
,但是由于某种原因,在获取数据后无法获取数据。
有没有办法用
答案 0 :(得分:2)
但是由于某种原因,即时通讯在获取数据后无法获取。
value
不属于该州,并且不会导致重新渲染。因此,您没有看到提取后显示更新的值。
要执行此操作,只需将value
设置为该状态的一部分以引起重新渲染。
state = {
value: 'Im not the correct value'
}
componentDidMount() {
// move side-effects in here
fetchContextFromAsycnService().then(value => this.setState({ value }));
}
render() {
return (
<AsyncContext.Provider value={this.state.value}>
<SomeComponent />
</AsyncContext.Provider>
);
}