我正在使用nextjs-react框架,正在使用getInitialProps
函数来创建初始属性,但是无法访问显示undefined
的该函数返回的值。我的代码是
import React, { Component } from 'react';
import fetch from 'isomorphic-unfetch'
import { connect } from 'react-redux'
import {addName} from '../Actions/actionCreators'
class about extends Component {
static async getInitialProps({ req }){
try{
const protocol = req.headers['x-forwarded-proto'] || 'http'
const baseUrl = req ? `${protocol}://${req.headers.host}` : ''
const url = `${baseUrl}/api/config`
const response = await fetch(url)
const configJson = await response.json()
return { apiUrl: url, configs: configJson }
}catch{
return { error: 'Could not load configs'}
}
}
constructor(props){
super(props)
this.state = { name: '', configs: props.configs }
this.addname = this.addname.bind(this)
}
addname(e){
e.preventDefault()
const name = e.target.name.value
this.setState({ name: name })
const newName = {
name : this.state.name
}
fetch(this.props.apiUrl, {
method: 'POST',
body: JSON.stringify(newName),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.catch(err => console.error('POST error', err));
}
render() {
console.log(this.props.apiUrl)
const markup = this.props.name.name.length > 0 ? this.props.name.name.map((elem, i) => (
<div key={i}>
{this.props.name.name[i]}
</div>
)) : <p></p>
return (
<div>
<h2> About me </h2>
{markup}
<p>This is muaz.I am a programmer and web developer also a doctor.Want To learn Let me know about yourself</p>
<form action="" onSubmit={this.addname}>
<br/>
<input type="text" name="name" placeholder="Your Name" />
<br/>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return{
submitform : (e) => {
e.preventDefault()
dispatch(addName(e.target.name.value))
}
}
}
const mapStateToProps = state => {
console.log(state.name)
return{
name : state.name
}
}
export default connect(mapStateToProps, mapDispatchToProps)(about)
我还使用了Redux
的gramework。我已经对以下示例进行了测试:https://github.com/zeit/next.js#fetching-data-and-component-lifecycle
那行得通,但我需要更复杂的数据结构,无论如何都无法正常工作。即使重新加载页面也是如此。我在http://localhost:3000/about
上运行它