首页 > 解决方案 > 使用 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 应该在那里吗?我应该如何修改这段代码?显然,我很困惑。

任何帮助,将不胜感激。

标签: reactjsreact-nativereduxreact-redux

解决方案


当你使用时,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>
    );
  }
}

推荐阅读