javascript - React.js:props.state 为空白(空)
问题描述
我想使用 React.js + Redux 的 Todo List。
我制作减速器文件:
import { ADD_POST, REMOVE_POST } from "../actions/index.jsx";
const initialState = {
title: "",
content: ""
};
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
case REMOVE_POST:
return state.filter(({ id }) => id !== action.id);
default:
return state;
}
}
而且,我编辑 App.js :
class App extends Component {
render() {
return (
<div className="App">
<Input />
<List posts={this.props.allPosts} />
</div>
);
}
}
const mapStateToProps = state => {
return {
allPosts: [state.title, state.content]
};
};
export default connect(mapStateToProps, null)(App);
而且,列表组件是...:
render() {
return (
<div>
<ul>
{this.props.posts.map((post, index) => (
<Item {...post} key={index} />
))}
</ul>
</div>
);
}
}
我遇到错误“无法读取未定义的属性 'map'”并且无法继续。
我该如何解决?
我指的是多个来源,但我遇到了困难,因为我只能看到一个“文本”状态的文本,以及两个像“标题”和“内容”状态的来源。
- - - -_使固定
我修复了错误,但 props.state 为空白。我添加了带有文本的输入标签,但它并没有改变一切。
--------行动
export const ADD_POST = "ADD_POST";
export const REMOVE_POST = "REMOVE_POST";
let nextId = 0;
export function addPost(title, content) {
return {
type: ADD_POST,
id: nextId++,
title,
content
};
}
export function removePost(id) {
return {
type: REMOVE_POST,
id
};
}
解决方案
我认为您对您所在州的数据类型感到困惑。以下代码段可能对您有用。我将您的状态保留为一个帖子数组,其中 initialState 是一个空数组。
所以在你的 reducer 文件中,将 initialState 初始化为:
import {
ADD_POST,
REMOVE_POST
} from "../actions/index.jsx";
const initialState = [];
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
case REMOVE_POST:
return state.filter(({
id
}) => id !== action.id);
default:
return state;
}
}
在 App.js 中,在函数 mapStateToProps 中,将 allPosts 映射到数组状态。
class App extends Component {
render() {
return (
<div className="App">
<Input />
<List posts={this.props.allPosts} />
</div>
);
}
}
const mapStateToProps = state => {
return {
allPosts: state
};
};
export default connect(mapStateToProps, null)(App);
推荐阅读
- c# - JSON字符串化不序列化?绑定问题
- html - 简洁设计的阅读器视图
- javascript - 我需要使用 Angular 在 DIV 标签中显示一些文本
- python - 使用带有 AJAX 的 POST 将数据发送到服务器
- reactjs - 在 TypeScript 中编写 HOC 作为装饰器?
- php - Laravel Eloquent : Eloquent 模型的生命周期是什么
- ffmpeg - FFMPEG 画框过滤器。十六进制颜色结果与输入值不匹配
- react-native - 如何在不启动系统对话框的情况下使用 Expo 在 React-Native 中静默检查相机权限?
- azure - 使用 U-SQL 删除字符串中的空行
- java - JDK 9 和 JDK 10 上的 Nashorn 性能