为什么fetch第二次没有工作?

时间:2018-06-18 20:40:15

标签: javascript reactjs express

这是一个非常烦人的事情,我现在正试图解决它几个小时。这是代码:

//ExpressJS code
    
app.post('/newname', (req, res) => {
    const {name, type, id} = req.body;
    console.log(name, type, id)
    knex('fl').insert({
        name, type, id,
        ...type === 'category'? {timeValue: req.body.timeValue, timeType: req.body.timeType} : {}
    })
    .then(() => {
        console.log("bar"); 
        return knex('fl').select('*').where('status', 'available')})
    .then(data => res.json(data))
    .catch(err => console.log(err))
})
    
    
    //React code
    
    possibleName = (event) => {
        this.setState({
            possibleName: event.target.value
        })
        console.log(this.state.possibleName)
    }
    
    complete = () => {
        if(Boolean(this.state.possibleName)){
            console.log(this.state.possibleName)
            fetch('http://localhost:3001/newname', {
                method: 'post',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    name: this.state.possibleName,
                    type: this.state.type,
                    id: this.props.id,
                    ...this.state.type === 'category'? {timeValue: this.props.timeValue, timeType: this.props.timeType}:{}
                })
            })
            .then(res => res.json())
            .then(data => {
                console.log("foo");
                this.props.dispatch(getAction(data));
                this.setState({
                    create: 'none',
                    zindex: 0,
                    possibleName: ''
                })
            })
            .catch(err => console.log(err))
        }
    }
    
    //...
    //...
    <input type='text' value={this.state.possibleName} onChange={this.possibleName}/>
    <div onClick={this.complete}></div>

所以......第一次点击div,一切正常。所有日志都在控制台中。第二次,complete()的第一次日志发生了,但似乎没有发生提取。什么原因?东西会阻止第二次获取?如果我使用Postman尝试它,使用相同格式的req.body,每次尝试时一切正常。所以我不知道会出现什么问题。

我认为可能是问题根源的另一件事是,有一个调度。 redux可能不会让fetch完成?我的意思是第一次提取开始,但没有完成,所以如果我第二次获取,它进入查询,并在获取完成之前开始?

0 个答案:

没有答案
相关问题