Я делаю вызов API, который возвращает мне массив имен пользователей. Я вызываю API в компоненте Navbar и отправляю данные, возвращаемые API, другому компоненту в качестве реквизита. Когда я console.info(this.state.Name) в Navbar, он дает весь массив с именами пользователей в консоли, но когда я получаю массив в другом компоненте SearchedUser и console.info() полученной опоры, он дает мне undefined в консоль. Может ли кто-нибудь сказать, что не так.
----------------------------------Компонент панели навигации----------------------------- --------------
class Navbar extends Component{
constructor(props){
super(props);
this.state = {
name:'',
Name:[],
}
this.GetUserData=this.GetUserData.bind(this);
}
GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.info(err));}
render()
{
console.info(this.state.Name);
return(
<Router>
<Link to = {'/SearchedUser'}>
<button type = "submit" onClick = {this.GetUserData}><i className = "fa fa-search"></i></button>
</Link>
<Switch>
<Route exact path='/' component = {HomeContent} />
<Route path='/Profile' component = {Profile}/>
<Route path='/SearchedUser' render = {(props)=> <SearchedUser {...props} UserName = { [this.state.Name]}/>}/>
</Switch>
</Router>) }}
--------------------------------Компонент SearchedUser---------------- --------
import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state = {
Name: props.UserName
}
}
render(){
console.info(this.state.Name);
return(
<div>
</div>
)
}
}
export default SearchedUser;
Ты можешь попробовать
console.info(this.props.UserName);
внутри render()
в компоненте SearchedUser.
Поскольку вы пытаетесь получить имя пользователя из конструктора, а по умолчанию компонент поиска будет получать значение null
в props.username
props.username
получит новое значение только после получения ответа на выборку.
Можете ли вы попробовать с 2 изменениями, например:
[this.state.Name]
> this.state.Name
, поскольку первый выводит массив с одной записью, например ['sara']
:
<SearchedUser {...props} UserName = {this.state.Name}/>}
Другое дело, в конструкторе компонента NavBar:
this.state = {
name:'',
Name:'',
}
Используйте componentWillReceiveProps для обновления состояния
import React from 'react'
class SearchedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
Name:[]
}
}
/** When the SearchedUser component does anything with the new props,
* componentWillReceiveProps is called, with the next props as the argument */
componentWillReceiveProps(nextProps) {
/** Update state**/
if (nextProps.UserName !== this.props.UserName) {
this.setState({
Name: nextProps.UserName
});
}
}
render() {
console.info(this.state.Name);
return ( <
div >
<
/div>
)
}
}
export default SearchedUser;
чувак, тебе нужно получить доступ к props
с помощью this.props.propsName
в компоненте класса.
//SearchedUser component
import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state = {
Name: this.props.UserName
}
}
render(){
return(
<div>
</div>
)
}
}
export default SearchedUser;
Да, я только что сделал это. Большое спасибо