我正在尝试将组件添加到带有React项目的默认.NET Core MVC中。我相信我已经将所有东西都连接起来以镜像现有的“获取数据”组件,但是似乎并没有真正调用它(但是导航栏中指向该组件的链接确实移到了新页面)。
组件本身...
import React, { Component } from 'react';
export class TestComponent extends Component {
static displayName = TestComponent.name;
constructor (props) {
super(props);
console.log("WHO NOW?");
this.state = { message: '', loading: true, promise: null };
this.state.promise = fetch('api/SampleData/ManyHotDogs');
console.log(this.state.promise);
}
static renderForecastsTable (message) {
return (
<h1>
Current Message: {message}
</h1>
);
}
render () {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: TestComponent.renderForecastsTable(this.state.message);
return (
<div>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
{contents}
</div>
);
}
}
App.js
import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { TestComponent } from './components/TestComponent';
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetch-data' component={FetchData} />
<Route path='/test-controller' component={TestComponent} />
</Layout>
);
}
}
在我检查时从未调用过console.log(“ Who now”),并且页面仍然完全空白。我找不到这和功能组件之间的关键区别,谷歌也没有太大的帮助。有什么想法吗?
编辑
在对此进行故障排除时,我最终创建了一个依赖噩梦,破坏了应用程序。由于我仅使用该应用程序来浏览React,因此我将其删除并重新开始-在第二次尝试中,我无法重现未渲染的问题。
答案 0 :(得分:2)
建议使用componentDidMount通过fetch或axios调用REST API。
class TestComponent extends Component{
constructor(props){
state = {promise: ''}
}
async componentDidMount () {
let promise = await fetch ('api / SampleData / ManyHotDogs');
this.setState ({promise});
console.log (promise);
}
render(){
return(
<div>{this.state.promise}</div>
);
}
}