【发布时间】:2017-10-21 02:29:37
【问题描述】:
class App extends Component {
constructor(){
super();
this.state = {
usuarios:[],
hayUsuarios: false
};
}
render() {
var usuarios = [];
usuarios = this.state.usuarios.map(function(u){
return <Usuario key={u.cId} id={u.cId} nombre={u.dNombre} pedirUsuarios={this.pedirUsuarios()} />
});
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<AdicionarUsuario pedirUsuarios={this.pedirUsuarios()}/>
{usuarios}
</div>
);
}
componentDidMount(){
this.pedirUsuarios();
}
pedirUsuarios = () =>{
fetch("https://shielded-escarpment-86252.herokuapp.com/usuarios.json")
.then( resp => resp.json() )
.then(json => this.setState({usuarios: json}))
.catch((err) => console.log(err));
}
}
AdicionarUsuario
class AdicionarUsuario extends Component{
constructor(){
super();
this.state = {nombre:""};
}
onChange = (event) =>{
this.setState({nombre: event.target.value});
}
adicionarUsuario = (event) =>{
event.preventDefault();
console.log(this.state.nombre);
this.enviarPost(this.state.nombre);
}
enviarPost = (nomb) =>{
let datos = {
method: 'POST',
body: JSON.stringify({nombre: nomb}),
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}
}
fetch("https://shielded-escarpment-86252.herokuapp.com/adicionarUsuario", datos)
.then(resp => resp.json())
.then(algo => this.actualizar(algo))
.catch(err => console.log(err));
}
actualizar = (json) =>{
console.log(json);
if(json.respuesta){
this.props.pedirUsuarios();
}
}
render(){
return(
<form onSubmit={this.adicionarUsuario}>
<label>Nombre:</label>
<input type="text" value={this.state.nombre} onChange={this.onChange} placeholder="Post"/>
<input type="submit" value="Adicionar"/>
</form>
);
}
}
乌苏里奥
class Usuario extends Component{
constructor(){
super();
}
render(){
return(
<div>
<h3>{this.props.nombre}</h3>
<SubirCancion id={this.props.id} />
<ActualizarUsuario id={this.props.id} />
<EliminarUsuario id={this.props.id} />
</div>
);
}
}
我得到: “只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState、replaceState 或 forceUpdate。这是一个无操作。”
EDIT1:TypeError:无法读取未定义的属性“pedirUsuarios”, 删除括号并没有解决问题。
EDIT2:添加了 AdicionarUsuario 和 Usuario 组件
EDIT3:这是 jsfiddle https://jsfiddle.net/JuanDavid31/69z2wepo/88446/
当子组件请求 i 时,我需要重新渲染 App 组件,问题是当 ajax 完成时子组件不会被渲染。有什么帮助吗?
【问题讨论】:
-
你能把
AdicionarUsuario的代码贴出来吗? -
我不太确定该应用程序应该做什么,因为它是西班牙语,但这是新的小提琴jsfiddle.net/smlacerda5/69z2wepo/88474 我不得不删除其中一个组件,因为它提供了一些关于巨蟹座???一切看起来都不错,除了你有一些 function(){ // 'this' 关键字是这里的窗口 } 并且你需要 () => { // 'this' 关键字是这里的组件 }
-
非常感谢!这就是我需要的
标签: javascript reactjs