Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Redux对象在提交时为空_Javascript_Reactjs_React Redux - Fatal编程技术网

Javascript Redux对象在提交时为空

Javascript Redux对象在提交时为空,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我在提交表单时遇到了一个问题,我的对象在提交时是空的,我也在redux开发工具中确认了这一点。当我提交表单时,一张卡片应该出现在DOM上,上面有我在表单中输入的信息,或者是传递给该组件的道具的信息。当我提交信息时,信息是空的,我的redux开发工具显示提交时对象是空的 这是我的帖子 export const postRecipes = (recipe) => { const BASE_URL = `http://localhost:3001` const RECIPE

我在提交表单时遇到了一个问题,我的对象在提交时是空的,我也在redux开发工具中确认了这一点。当我提交表单时,一张卡片应该出现在DOM上,上面有我在表单中输入的信息,或者是传递给该组件的道具的信息。当我提交信息时,信息是空的,我的redux开发工具显示提交时对象是空的

这是我的帖子

export const postRecipes = (recipe) => {
  
    const BASE_URL = `http://localhost:3001`
    const RECIPES_URL =`${BASE_URL}/recipes`
    const config = {
        method: "POST",
        body:JSON.stringify(recipe),
        headers: {
        "Accept": "application/json",
        "Content-type": "application/json"
     }
    }

    return (dispatch) => {
      
      fetch(RECIPES_URL,config)
        .then(response =>{ response.json()})
        .then(recipe => { dispatch({ type: 'ADD_RECIPE', payload: recipe })
        
    })
    .catch((error) => console.log.error(error))
       
        
    };

    
    
  }

编辑:为检索保存到数据库中的食谱添加了获取操作

export const getRecipes = () => {
  
    const BASE_URL = `http://localhost:3001`
    const RECIPES_URL =`${BASE_URL}/recipes`

    return (dispatch) => {
      dispatch({ type: 'START_FETCHING_RECIPES_REQUEST' });
      fetch(RECIPES_URL)
        .then(response =>{ return response.json()})
        .then(recipes => { dispatch({ type: 'GET_RECIPES', recipes })});
       
        
    };

    
    
  }
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import manageRecipes from './reducers/manageRecipes';
import 'bootstrap/dist/css/bootstrap.min.css';
import { composeWithDevTools } from 'redux-devtools-extension'

const composeEnhancer = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(manageRecipes,composeEnhancer)

ReactDOM.render(
  
    <Provider store={store}>
    <App />
    </Provider>,
   
  document.getElementById('root')
);
这是我添加对象的reducer操作类型(希望我的措辞正确)

编辑:为请求添加还原剂请参见我的食谱的当前状态

case 'START_FETCHING_RECIPES_REQUEST':
            return {
                ...state,
            recipes: [...state.recipes],
            loading: true
        }
        case 'GET_RECIPES':
            return {
                ...state, recipes: action.recipes,
                loading: false
            }
const mapStateToProps = state =>{
    return{
        recipes: state.recipes,
        loading: state.loading

    }
}


const mapDispatchToProps = dispatch =>{
    return{
    postRecipes: recipe => dispatch(postRecipes(recipe)),
    getRecipes: () => dispatch(getRecipes()),
    deleteRecipe: recipeId => dispatch(deleteRecipe(recipeId))
    }
}
编辑:我的mapDispatchToProps和mapDispatchToState函数

case 'START_FETCHING_RECIPES_REQUEST':
            return {
                ...state,
            recipes: [...state.recipes],
            loading: true
        }
        case 'GET_RECIPES':
            return {
                ...state, recipes: action.recipes,
                loading: false
            }
const mapStateToProps = state =>{
    return{
        recipes: state.recipes,
        loading: state.loading

    }
}


const mapDispatchToProps = dispatch =>{
    return{
    postRecipes: recipe => dispatch(postRecipes(recipe)),
    getRecipes: () => dispatch(getRecipes()),
    deleteRecipe: recipeId => dispatch(deleteRecipe(recipeId))
    }
}
编辑:包括我创建的店铺

export const getRecipes = () => {
  
    const BASE_URL = `http://localhost:3001`
    const RECIPES_URL =`${BASE_URL}/recipes`

    return (dispatch) => {
      dispatch({ type: 'START_FETCHING_RECIPES_REQUEST' });
      fetch(RECIPES_URL)
        .then(response =>{ return response.json()})
        .then(recipes => { dispatch({ type: 'GET_RECIPES', recipes })});
       
        
    };

    
    
  }
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import manageRecipes from './reducers/manageRecipes';
import 'bootstrap/dist/css/bootstrap.min.css';
import { composeWithDevTools } from 'redux-devtools-extension'

const composeEnhancer = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(manageRecipes,composeEnhancer)

ReactDOM.render(
  
    <Provider store={store}>
    <App />
    </Provider>,
   
  document.getElementById('root')
);
从“React”导入React;
从“react dom”导入react dom;
导入“./index.css”;
从“./App”导入应用程序;
从'react redux'导入{Provider};
从“redux”导入{createStore,applyMiddleware};
从“redux thunk”导入thunk;
从“./reducers/manageRecipes”导入manageRecipes;
导入'bootstrap/dist/css/bootstrap.min.css';
从'redux devtools extension'导入{composeWithDevTools}
常量composeEnhancer=composeWithDevTools(applyMiddleware(thunk))
const store=createStore(manageRecipes、composeEnhancer)
ReactDOM.render(
,
document.getElementById('root'))
);
编辑:我相信我在这段代码中添加了一些东西 下面是当用户与submit按钮交互时发出的事件处理程序

import React, { Component } from 'react'
import Select from 'react-select'
import axios from 'axios'
import '../index.css'



class RecipeInput extends Component{
    constructor(props){
        super(props)
        this.state = {
            
            category_id: [],
            name:'',
            ingredients: '',
            chef_name: '',
            origin: '',
            instructions:''
            
        }
        

        
    }


      

    
    async getOptions(){
        const BASE_URL = `http://localhost:3001`
        const CATEGORIES_URL =`${BASE_URL}/categories`
        const res = await axios.get(CATEGORIES_URL)
        const data = res.data

        const options = data.map(d => ({
           
            
           
            'label' : d.category,
            'id' : d.id

            
        }))

        this.setState({category_id: options})
    }

    

    handleNameChange = (event) =>{
        this.setState({name:event.target.value})
    }

    handleInsChange = (event) =>{
        this.setState({instructions:event.target.value})
    }

    handleIngChange = (event) =>{
        this.setState({ingredients:event.target.value})
    }

    handleChefChange = (event) =>{
        this.setState({chef_name:event.target.value})
    }

    handleOriginChange = (event) =>{
        this.setState({origin:event.target.value})
    }

    handleChange = (event) =>{
        
        this.setState({category_id:event.id})
    }

    componentDidMount(){
        this.getOptions()
    }


    handleSubmit = (event) =>{
        alert(this.state.name + 'was set!')
        event.preventDefault();
        this.props.postRecipes(this.state)
        this.setState({
        name:'',
        ingredients: '',
        chef_name: '',
        origin: '',
        instructions: ''
       })
     
     
    }

    

    
    
        

    render(){
       let dropdown = 'form-select form-select-sm'
  
        return(
            <div>
                
                <form onSubmit={this.handleSubmit}>
                    <Select options={this.state.category_id} onChange={this.handleChange} className={dropdown}/>
                    <div>
                    <label for='name'>Recipe Name:</label>
                    <input  className ="form-control" type='text' value={this.state.name} onChange={this.handleNameChange} />
                    </div>
                    <div>
                    <label for='name'>Country Origin:</label>
                    <input className ="form-control" type='text' value={this.state.origin} onChange={this.handleOriginChange} />
                    </div>
                    <div>
                    <label for='name'>Chef Name:</label>
                    
                    <input className ="form-control" type='text' value={this.state.chef_name} onChange={this.handleChefChange} />
                    </div>
                    <div>
                    <label for='name'>Ingredients:</label>
                    <textarea className ="form-control" cols="30" rows="5" type='text' value={this.state.ingredients} onChange={this.handleIngChange} />
                    
                    <label for='name'>Instructions:</label>
                    <textarea className ="form-control" cols="30" rows="5" type='text' value={this.state.instructions} onChange={this.handleInsChange} />
                    </div>
                    <input value='submit' type='submit'/>
                </form>
                
            </div>
        )
    }


 


}

export default RecipeInput
import React,{Component}来自“React”
从“反应选择”导入选择
从“axios”导入axios
导入“../index.css”
类RecipeInput扩展组件{
建造师(道具){
超级(道具)
此.state={
类别id:[],
名称:“”,
成分:'',
厨师长姓名:'',
来源:'',
说明:“”
}
}
异步getOptions(){
常量基本URL=`http://localhost:3001`
const CATEGORIES\u URL=`${BASE\u URL}/CATEGORIES`
const res=wait axios.get(CATEGORIES\u URL)
常数数据=分辨率数据
const options=data.map(d=>({
“标签”:d.类别,
“id”:d.id
}))
this.setState({category_id:options})
}
handleNameChange=(事件)=>{
this.setState({name:event.target.value})
}
HandleInChange=(事件)=>{
this.setState({指令:event.target.value})
}
handleIngChange=(事件)=>{
this.setState({成分:event.target.value})
}
handleChefChange=(事件)=>{
this.setState({chef_name:event.target.value})
}
HandleOrigingChange=(事件)=>{
this.setState({origin:event.target.value})
}
handleChange=(事件)=>{
this.setState({category_id:event.id})
}
componentDidMount(){
这个文件名为getOptions()
}
handleSubmit=(事件)=>{
警报(已设置this.state.name+'s!')
event.preventDefault();
this.props.postRecipes(this.state)
这是我的国家({
名称:“”,
成分:'',
厨师长姓名:'',
来源:'',
说明:“”
})
}
render(){
let下拉菜单='form select form select sm'
返回(
配方名称:
原产国:
厨师姓名:
成分:
说明:
)
}
}
导出默认RecipeInput

我觉得这是在我的行动后的某个地方,但不确定在哪里,我如何纠正这一点?

我理解这一点的方式,我可能是错误的,但这是我的理解

在RecipeInput类中,调用handleSubmit()。在该函数中,您使用this.state调用postRecipes()

将this.state变量初始化为以下值后,在何处设置该变量

this.state = {
            category_id: [],
            name:'',
            ingredients: '',
            chef_name: '',
            origin: '',
            instructions:''
            
        }

因此fetch(RECIPES_URL,config)中的post请求将发送一个空对象。因此,要更改此设置,您必须在调用postRecipes()函数之前设置this.states。

我将更新我的代码段,出于实际原因,我减少了此设置。这不是完整的输入组件。我已更新了那里的代码,以便您可以查看状态的设置方式。
handleSubmit=(e)=>{e.preventDefault();This.setState({name:'',Components:'',chef_name:'',origin:'',instructions:'')This.props.postRecipes(This.state)}
通过调用this.setState()您不是正在清除数据吗?然后将状态发送到函数?我以为我在提交后重置了表单。另外,我将调用postRecipe函数的那一行放回setSet-part方法上方,同样的问题也发生了。这就是我在这之前的情况