我正在使用PubSub全球化React应用程序上的某些状态。我有一个“主页”和一个“ Escolas”组件,“ Escolas”已经在使用PubSub与一个名为“过滤器”的组件共享其状态。效果很好。
但是,现在,我的用户在“主页”上启动了应用程序,在那输入了一个名称,我想将此值保存在PubSub主题中,但是当我尝试发布时,返回值为false。
setEscola(collection, e) {
this.setState({ escola: e });
var isPublished = PubSub.publish('escola-filtro', collection);
console.log(isPublished);
}
这是我的整个组件:
import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import lupa from '../../img/lupa.png';
import { Link } from 'react-router-dom';
import MenuHome from '../MenuSuperior/MenuHome';
import { listarEscolas } from '../../services/escolas';
import SelectAutocomplete from '../Inputs/SelectAutocomplete';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
escola : '',
escolas : []
}
this.setEscola = this.setEscola.bind(this);
this.testeEstado = this.testeEstado.bind(this);
}
componentDidMount() {
listarEscolas().then(
lista => {
let escolas = [];
lista.results.forEach(function(escola) {
escolas.push({value : escola.codesc, label : escola.nomesc })
});
this.setState({ escolas : escolas });
}
)
}
componentWillMount() {
PubSub.clearAllSubscriptions();
}
buscarEscolas = (e) => {
if (e.target.value.length >= 3) {
let escolas = [];
listarEscolas(e.target.value).then(
lista => {
lista.results.forEach(function(escola) {
escolas.push({value : escola.codesc, label : escola.nomesc });
});
this.setState({ escolas : escolas });
}
)
}
}
setEscola(collection, e) {
// this.setState({ escola: e });
// var isPublished = PubSub.publishSync('escola-filtro', collection);
// console.log(isPublished);
}
testeEstado(event) {
console.log(event.target.value);
var isPublished = PubSub.publishSync('filtro', event.target.value);
console.log(isPublished);
}
render() {
return(
<div>
<MenuHome />
<div className="w-100 mapa-home">
<div className="container d-flex justify-content-center">
<div className="col-lg-5 text-center position-absolute conteudo">
<h2>Aqui você encontra todas as informações sobre sua escola</h2>
<div className="form-group mt-4">
<input type="text" className="form-control form-control-lg" onChange={this.testeEstado} />
<SelectAutocomplete
value={this.state.escola}
collection={this.state.escolas}
className="form-control form-control-lg rounded-pill shadow m-90 d-inline-block"
placeholder="Encontre sua escola pelo nome ou bairro"
onChange={this.setEscola}
onKeyDown={this.buscarEscolas}
/>
<Link className="btn btn-light d-inline-block ml-1" to="/escolas"><img src={lupa} alt="Buscar" /></Link>
</div>
</div>
</div>
</div>
</div>
);
}
}
答案 0 :(得分:0)
尝试一下:
async function testeEstado(event) {
console.log(event.target.value);
var isPublished = await PubSub.publishSync('filtro', event.target.value);
console.log(isPublished);
}
Async Await模型应该可以在这里尝试测试。我不确定如果这些问题更根本,是否能够解决问题。