我有一个外部文件,其中我声明要导入我的全局变量。
BOQSuggestions.js
var BOQSuggestions = []
export default BOQSuggestions;
我在 TasksInsert.jsx 中导入全局变量,如下所示:
import BOQSuggestions from './BOQSuggestions';
在我的 render()
函数的 return
部分,我有以下代码:
return (
<Wrapper>
<Title>Insert a Task</Title>
<Label>Description: </Label>
<InputText
type="text"
placeholder="Search for tasks in the BOQ..."
value={ taskName }
onChange={this.handleChangeInputTaskName}
/>
<h1>{BOQSuggestions.length}</h1>
...
我的handleChangeInputTaskName函数如下:
handleChangeInputTaskName = async event => {
var taskName = event.target.value
if(taskName.charAt(taskName.length -1) == ' '){
api.autoCompleteBOQ(taskName).then(res => {
var autoresultArray = res.data.data.hits.hits
var autoResult = []
for(var i = 0; i < autoresultArray.length; i++){
autoResult = (JSON.stringify(autoresultArray[i]._source.boqList))
BOQSuggestions.push(JSON.stringify(autoresultArray[i]._source.boqList))
}
console.log('Length of the suggestions array ====> ', BOQSuggestions.length )
}).catch(error => {
console.log('Some error got while performing autocomplete ')
})
}
this.setState({taskName})
}
我在 handleChangeInputTaskName
函数中获得了正确的 BOQSuggestions.length
值,但是在返回函数中,长度值始终保持为零。
我是否可以维护这个变量的状态,因为它已作为全局变量导入?我不想为此目的使用 Redux 或任何其他库,因为这是我唯一需要状态保持一致的地方。
我对 React 和 Javascript 都比较陌生。请帮帮我。谢谢!
最佳答案
您好,我认为在您的方法 handleChangeInputName 中,您正在改变 BOQSuggestions.js 中的数据,为什么您不更改应用程序的状态而不是这个?也许尝试这样的事情:
如果您使用 BOQSuggestions 的导入值来初始化您的状态:
constructor(props) {
super(props)
this.state = {
projectId: this.props.match.params.id,
BOQSuggestions : BOQSuggestions ,
} };
在您的 handleChangeInputName 中,您应该以这种方式更新 Prop :
handleChangeInputTaskName = async event => {
var taskName = event.target.value
var tempBOQ = this.state.tempBOQ;
if(taskName.charAt(taskName.length -1) == ' '){
api.autoCompleteBOQ(taskName).then(res => {
var autoresultArray = res.data.data.hits.hits
var autoResult = []
for(var i = 0; i < autoresultArray.length; i++){
autoResult = (JSON.stringify(autoresultArray[i]._source.boqList))
// Here instead of mutating BOQSuggestion imported value
// You should modify the state property of BOQSuggestion
tempBOQ = [...tempBOQ, JSON.stringify(autoresultArray[i]._source.boqList)]
}
// So here you should check the length of the tempBOQ instead of the BOQSuggestions
console.log('Length of the suggestions array ====> ', tempBOQ.length )
}).catch(error => {
console.log('Some error got while performing autocomplete ')
})
}
// And here in the setState Method you should update the BOQSugegstions
// Anbd maybe just to confirma that everything updated correctly use the callback of the setState To check when the data was already updated
this.setState({taskName, BOQSuggestions: tempBOQ}, () => { console.log(this.state.BOQSuggestions)})
}
请记住,setState
方法是异步,因此如果您在调用它后立即检查它,则该值可能不会更新。
现在每次您想使用您的BOQSuggestions时,您都应该访问它:this.state.BOQSuggestions
关于javascript - 无法读取数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380338/