我想使用unstated.js(React Context包装器)使用来自api调用的数据来简单地初始化Container状态。
我看到了一个示例,其中用几个变量实例化了容器:
import { Container} from 'unstated';
class WordlistContainer extends Container {
constructor(...words) {
super();
this.state = {
words: words
};
}
}
let wordList = new WordlistContainer('word1', 'word2');
export default wordList;
如果我想获取一些api数据以传递到此Container的状态-这是正确的方法吗?还是应该从父级组件传递道具?这是用于在首次加载数据时将数据加载到SPA中。
答案 0 :(得分:3)
这最终成功了:
import React, { Component } from 'react';
import RDOM from 'react-dom';
import { Container, Provider, Subscribe } from 'unstated';
class ApiContainer extends Container {
state = {
loading: true,
data: null
}
setApiResponseAsState = async () => {
fetch.('someapi').then(res => res.jsoj()).then( data => this.setState({ data, loading: false });
}
}
class ApiConsumer extends Component {
async componentDidMount() {
this.props.setApiResponseAsState();
}
render() {
return <div>{this.props.state}</div>
}
}
RDOM.render(
<Provider>
<Subscribe to={[ApiContainer]}>
{ props => <ApiConsumer {…props} />
}
</Subscribe>
</Provider>
, document.querySelector("#root");
)
答案 1 :(得分:2)
直接方法是使用容器的实例。
WordlistContainer
的示例实现:
export default class WordlistContainer extends Container {
fetchWords = async () => {
const result = await fetch('https://example.com')
const words = await result.json()
this.setState({ words })
}
// etc... the rest of the container's code
}
// in this and most cases we want a singleton (but other instances can be created)
const wordlistContainer = new WordlistContainer()
export const getWordlistContainerInstance = () => wordlistContainer
然后,将该实例注入提供程序中,例如:
<Provider inject={[getWordlistContainerInstance()]}>
可以通过调用任何地方来触发获取
getWordlistContainerInstance().fetchWords()