reactjs - 我在 mapStateToProps 中的状态未定义
问题描述
我在其他有关此问题的问题之后遇到了问题,所以这里什么都没有。
所以我正在使用 redux thunk 来“发布”到数据库,并希望使用 fetch 显示在前端视图上......但这还不是我的问题所在,只是想让你了解我在某个时候想要结束的地方. 所以我的问题是我的 mapStateToProps 函数上出现“TypeError:state is undefined”,我认为我设置正确。
下面是显示在我的浏览器中的代码片段,显示了问题所在。
0 | const mapStateToProps = state =>{
31 | return{
> 32 | recipes: state.recipes,
33 | }
34 | }
35 |
.....我希望我不会在下一部分失去任何人
到目前为止......这是我的 RecipeContainer 组件,其中定义并连接了我的 mapStateToProp 函数。
import React, { Component } from 'react'
import RecipeList from '../components/RecipeList'
import RecipeInput from '../components/RecipeInput'
import { connect } from 'react-redux'
import { postRecipes } from '../actions/fetchRecipes.js'
class RecipeContainer extends Component{
constructor(props){
super(props)
}
componentDidMount(){
this.props.postRecipes()
}
render(){
return (
<div>
<RecipeInput addRecipe={this.props.addRecipe}/>
<RecipeList recipes={this.props.recipes} deleteRecipe={this.props.deleteRecipe}/>
</div>
)
}
}
const mapStateToProps = state =>{
return{
recipes: state.recipes,
}
}
const mapDispatchToProps= dispatch =>{
return{
addRecipe: () => dispatch(postRecipes()),
deleteRecipe: id => dispatch({type: 'Delete_Recipe', id})
}
}
export default connect(mapStateToProps,mapDispatchToProps)(RecipeContainer)
这是我的减速器,显示了我将“Add_Recipe”操作类型放在一起的位置
import cuid from 'cuid';
export const cuidFn = cuid
export default function manageRecipes(state={
recipes:[],
catagories:[],
}, action){
switch(action.type){
case 'Add_Recipe':
const recipe = {
name: action.name,
ingredients: action.ingredients,
chef_name: action.chef_name,
origin: action.origin,
catagoryId: action.catagoryId,
catagories: action.catagories,
id: cuidFn()
}
return{
...state,
recipes: [...state.recipes, recipe],
}
}
最后(不确定这有多相关).....这是我在它自己的文件中定义的“postRecipe”操作
export function postRecipes(){
const BASE_URL = `http://localhost:10524`
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(resp => {
dispatch({
type: 'Add_Recipe',
paylaod:{
name: resp.name,
ingredients: resp.ingredients,
chef_name: resp.chef_name,
origin: resp.origin,
catagoryId: resp.catagoryId
}
})
})
.catch((error) => console.log.error(error))
}
}
我基本上想知道我在 mapStateToProp 函数中最初提到的状态是如何出现未定义的,以及我是否遗漏了我提供的代码中的任何内容。Redux 有点难以掌握。
解决方案
推荐阅读
- unit-testing - Visual Studio Enterprise 2019,“配置文件”单元测试导致错误:文件不包含数据缓冲区
- powershell - 如何从 https://www.googleapis.com/oauth2/v3/certs 生成符合 PEM 或 x509 的证书?
- python - python中的模板化对象生成
- php - 如何将数组写入文件 PHP?
- swift - 刷新视图时,UILabel 不会替换以前的文本
- javascript - 循环未在 dom 中写入预期输出 15 次
- ios - JustLog中的NSURLAuthenticationMethodServerTrust质询启用logstash日志记录到logz.io
- node.js - Nodejs,sqllite3数据类型问题
- wpf - 将行绑定到与 wpf 中 datagrid 列中的按钮关联的上下文菜单项
- gcc - GCC、glfw、ImGui 上的链接错误,很高兴