javascript Reactjs:如何在安装组件之前获取要加载的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33091183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reactjs: How to fetch data to loaded before the component is mounted?
提问by Non
Something weird is happening, I've been reading the React docs and they talk about the lifecycle and how you can do somestuff before your component is rendered. I am trying, but everything I try is failing, always the component makes the render first and after calls componenWillMount, ..didMount, etc.. and after the call of those functions, the render happens again.
发生了一些奇怪的事情,我一直在阅读 React 文档,他们讨论了生命周期以及如何在呈现组件之前做一些事情。我正在尝试,但我尝试的一切都失败了,组件总是先进行渲染,然后在调用 componenWillMount、..didMount 等之后进行渲染,在调用这些函数后,渲染再次发生。
I need to load the data first in order to fill the state because I don't want initial state to be null
, I want it with data since the initial rendering.
我需要先加载数据以填充状态,因为我不希望初始状态为null
,我希望它具有自初始渲染以来的数据。
I am using Flux and Alt, here is the
我正在使用 Flux 和 Alt,这是
action
行动
@createActions(flux)
class GetDealersActions {
constructor () {
this.generateActions('dealerDataSuccess', 'dealerDataFail');
}
getDealers (data) {
const that = this;
that.dispatch();
axios.get(`${API_ENDPOINT}/get-dealers/get-dealers`)
.then(function success (response) {
console.log('success GetDealersActions');
that.actions.dealerDataSuccess({...response.data});
})
}
}
then the store
然后是商店
@createStore(flux)
class GetDealersStore {
constructor () {
this.state = {
dealerData : null,
};
}
@bind(GetDealersActions.dealerDataSuccess)
dealerDataSuccess (data) {
this.setState({
dealerData : data,
});
}
}
and the component
和组件
@connectToStores
export default class Dealers extends Component {
static propTypes = {
title : React.PropTypes.func,
}
static contextTypes = {
router : React.PropTypes.func,
}
constructor (props) {
super(props);
this.state = {
modal : false,
dealerData : this.props.dealerData,
}
}
componentWillMount () {
GetDealersActions.getDealers();
this.setState({
dealerData : this.props.dealerData.dealersData,
})
}
static getStores () {
return [ GetDealersStore ];
}
static getPropsFromStores () {
return {
...GetDealersStore.getState(),
}
}
render () {
return (<div>
<div style={Styles.mainCont}>
{!!this.props.dealerData ?
this.props.dealerData.dealersData.map((dealer) => {
return (<div>HERE I AM RENDERING WHAT I NEED</div>);
}) : <p>Loading . . .</p>
}
</div>
</div>
);
}
}
as you can see in the component part I have this
正如您在组件部分中看到的那样,我有这个
constructor (props) {
super(props);
this.state = {
modal : false,
dealerData : this.props.dealerData,
}
}
componentWillMount () {
GetDealersActions.getDealers();
this.setState({
dealerData : this.props.dealerData.dealersData,
})
}
which is telling me that dealerData is undefined
or can not read property of null
.
这是告诉我那个dealerData is undefined
或can not read property of null
。
All I need is to know a technique where I can fetch the data before the initial renders occurs. So I can filled out the state
and the start working with that data.
我所需要的只是知道一种可以在初始渲染发生之前获取数据的技术。所以我可以填写state
并开始使用这些数据。
回答by E_net4 the Rustacean
React does guarantee that state assignments in componentWillMount
will take place before the first render. As you well stated in the comments:
React 确实保证状态分配componentWillMount
将在第一次渲染之前发生。正如您在评论中所说的那样:
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.
在客户端和服务器上调用一次,紧接在初始呈现发生之前。如果您在此方法中调用 setState,render() 将看到更新的状态,并且尽管状态发生变化也只会执行一次。
However, the asynchronous actions requested there will not immediately update your store. Calling GetDealersActions.getDealers();
will issue that the store is updated with new content, but the response will only arrive later in the event queue. This means that this.props.dealersData
does not change during the function and setState
will attempt to read property "dealersData" of an undefined property. Regardless, the requested content cannot be visible at the first render.
但是,那里请求的异步操作不会立即更新您的商店。调用GetDealersActions.getDealers();
将发出用新内容更新商店的信息,但响应只会稍后到达事件队列。这意味着this.props.dealersData
在函数运行期间不会改变并且setState
将尝试读取未定义属性的属性“dealersData”。无论如何,请求的内容在第一次渲染时是不可见的。
My advice is the same as the one in a similar question. Preventing the component from rendering that content until it becomes available, as you did, is an appropriate thing to do in a program. Alternatively, render a loader while your "dealersData" hasn't arrived.
我的建议与类似问题中的建议相同。像您一样,在该内容可用之前阻止组件呈现该内容是在程序中做的合适的事情。或者,在您的“dealersData”尚未到达时呈现加载器。
For solving your particular problem, remove that setState
from componentWillMount
. All should work well if your parent component is properly listening for changes and propagating them to the children's props.
为了解决您的特定问题,请将其setState
从componentWillMount
. 如果您的父组件正确地侦听更改并将它们传播到子组件的 props,那么一切都应该运行良好。
componentWillMount () {
GetDealersActions.getDealers();
}
回答by Asmaa Almadhoun
The best answer I use to receive data from server and display it
我用来从服务器接收数据并显示它的最佳答案
constructor(props){
super(props);
this.state = {
items2 : [{}],
isLoading: true
}
}
componentWillMount (){
axios({
method: 'get',
responseType: 'json',
url: '....',
})
.then(response => {
self.setState({
items2: response ,
isLoading: false
});
console.log("Asmaa Almadhoun *** : " + self.state.items2);
})
.catch(error => {
console.log("Error *** : " + error);
});
})}
render() {
return(
{ this.state.isLoading &&
<i className="fa fa-spinner fa-spin"></i>
}
{ !this.state.isLoading &&
//external component passing Server data to its classes
<TestDynamic items={this.state.items2}/>
}
) }