reactjs - 使用 redux 反应原生 post 数据
问题描述
我正在尝试将数据发布到带有 redux 存储的 api,但我很难理解整个逻辑。
我的 ActionCreators 中有一个 postComment 函数,它基本上将 api 的响应添加到 comments 数组中。
export const postComment = (comment) => (dispatch) => {
return fetch(baseUrl + 'testResults', {
method: 'POST',
body: JSON.stringify({
comment:comment
}),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
if (response.ok) {
return response;
}
else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
var errmess = new Error(error.message);
throw errmess;
})
.then(response => response.json())
.then(response => dispatch(addComments(response)))
.catch(error => { console.log('Post comments ', error.message);
alert('Your comment could not be posted\nError: '+ error.message); })
}
export const addComments = (comments) => ({
type: ActionTypes.ADD_COMMENTS,
payload: comments
});
我的 redux 文件夹下有相应的 ActionTypes 和 comments.js 文件。
现在我的问题是如何触发这个 postComment 函数?
假设我有这样的 CommentComponent 文件
const mapStateToProps = state => {
return {
comments: state.comments
}
}
const mapDispatchToProps = dispatch => ({
postComment: (comment) => dispatch(postComment(comment))
})
class CommentsExample extends Component{
handleSubmit = () => {
}
render() {
return (
<View>
<TextInput
style={{height: 40}}
placeholder="Type your Comment here"
onChangeText={(text) => this.setState({text})}
/>
<Button
title="Submit"
onPress={this.handleSubmit}
/>
</View>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CommentsExample);
在我的 handleSubmit 函数中做什么?mapDispatchToProps 应该在那里吗?我应该如何修改这段代码?显然,我很困惑。
任何帮助,将不胜感激。
解决方案
当你使用时,connect
你基本上告诉 redux 为你的组件提供新的 props,这些 props 由mapStateToProps
和指定mapDispatchToProps
。
因此,在您的示例中,CommentsExample
现在可以访问由 connect 创建的两个道具:comments
(created by mapStateToProps
) 和postComment
(created by mapDispatchToProps
)。
为了调度postComment
动作,您可以使用提供的道具handleSubmit
:
handleSubmit = () => {
this.props.postComment(this.state.text)
}
同样要在组件中使用状态,您需要首先创建状态对象,这是完整的示例:
class CommentsExample extends Component {
state = {
text: '',
}
handleSubmit = () => {
this.props.postComment(this.state.text);
}
render() {
return (
<View>
<TextInput
style={{height: 40}}
placeholder="Type your Comment here"
onChangeText={(text) => this.setState({text})}
/>
<Button
title="Submit"
onPress={this.handleSubmit}
/>
</View>
);
}
}
推荐阅读
- r - 如何检测是否没有引用向量中的所有元素
- javascript - 使用条件语句和 IIAEF 等待/异步
- python - Django:在 ListView 中显示评分计数
- typescript - 如何在 TypeScript 函数的参数中声明新的泛型?
- vue.js - 在使用 NuxtJS 或 NextJS 时,是否可以根据需要在 URL 末尾添加 .html?
- visual-studio-code - vscode 的默认 javascript 格式化程序插件是什么?
- c++ - C++ 从 txt 文件中的两列读取和存储变量
- apache-spark - 如何合并pyspark中的重复列?
- html - 如何使用外部 css 来定位:空白;
- java - Flink 任务对取消信号 30 秒没有反应,但卡在方法中