Reactjs 将值从组件传递到redux存储

Reactjs 将值从组件传递到redux存储,reactjs,react-redux,Reactjs,React Redux,我有一个投票按钮,上面有很多票,当我点击投票按钮时,我看到一个+/-没有正确的票数。我把数字硬编码为12,我可以投赞成票或反对票 尽管我不知道如何用计数的实际API值动态填充按钮 以下是组件中api调用的正确值:count={api.voteScore} 还要注意减速器/动作集\u表决\u计数 代码如下: API fetch.js import React, {Component} from 'react'; import AddButton from './AddButton' class

我有一个投票按钮,上面有很多票,当我点击投票按钮时,我看到一个+/-没有正确的票数。我把数字硬编码为12,我可以投赞成票或反对票

尽管我不知道如何用计数的实际API值动态填充按钮

以下是组件中api调用的正确值:
count={api.voteScore}
还要注意减速器/动作集\u表决\u计数

代码如下:

API fetch.js

import React, {Component} from 'react';
import AddButton from './AddButton'

class Posts extends Component {
constructor(props) {
    super(props);

    this.state = {
        response: ''
    };
}

componentDidMount() {
    getPostAsync('/posts').then(data => this.setState({ response: data }));
}

render() {

    return (
    <div className="App">
        <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />

        {Array.isArray(this.state.response) &&
            this.state.response.map(api => <>

                { api.voteScore}
                {console.log(api.voteScore)}

                <AddButton className="voting"
                    count={api.voteScore} />
                <p> { api.title }, by { api.author } </p>
                <p> { api.body } </p>
                <p> {api.category} </p>
            </>
        )}

        </header>
    </div>
    )
}
}
async function getPostAsync(api) {
    let response = await fetch(api);
    let data = await response.json()
    return data;
}

export default Posts;
import React from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    setVoteCount: () => dispatch({ type: 'SET_VOTE_COUNT', count: '12' }),
  }
}

const AddButton = props => (
  <div className="voting">
    <button onClick={() => {
      console.log(props.setVoteCount(props.count));
    }}>
      Vote
    </button>
  </div>
);


export default connect(null, mapDispatchToProps)(AddButton);
export const setVoteCount = (id) => {
    return {
        type: "SET_VOTE_COUNT",
        count: '',
        id
    };
}
import { createStore, applyMiddleware, compose } from 'redux';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const change_counter = (state = {}, action) => {
    switch (action.type) {

        case "SET_VOTE_COUNT":
        if (state.id !== action.id) {
            return state;
        }
        return {
                ...state,
        }
        case "INCREMENT":
        if (state.id !== action.id) {
            return state;
        }
        return {
            ...state,
            count: parseInt(state.count) + 1
        };
        case "DECREMENT":
        if (state.id !== action.id) {
            return state;
        }

        return {
            ...state,
            count: parseInt(state.count) - 1
        };
        default:
        return state;
    }
    };
    let nextId = 0;
    const counters = (state = [], action) => {
        switch (action.type) {
        case "ADD_COUNTER":
            return [...state, {id: nextId++, count: 0}];
        case "SET_VOTE_COUNT":
                return [...state, {id: nextId++, count: action.count}];
        case "INCREMENT":
            return state.map(counter => change_counter(counter, action));
        case "DECREMENT":
            return state.map(counter => change_counter(counter, action));
        default:
            return state;
        }
    }
    export default createStore(counters, composeEnhancers(applyMiddleware()));
reducer.js

import React, {Component} from 'react';
import AddButton from './AddButton'

class Posts extends Component {
constructor(props) {
    super(props);

    this.state = {
        response: ''
    };
}

componentDidMount() {
    getPostAsync('/posts').then(data => this.setState({ response: data }));
}

render() {

    return (
    <div className="App">
        <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />

        {Array.isArray(this.state.response) &&
            this.state.response.map(api => <>

                { api.voteScore}
                {console.log(api.voteScore)}

                <AddButton className="voting"
                    count={api.voteScore} />
                <p> { api.title }, by { api.author } </p>
                <p> { api.body } </p>
                <p> {api.category} </p>
            </>
        )}

        </header>
    </div>
    )
}
}
async function getPostAsync(api) {
    let response = await fetch(api);
    let data = await response.json()
    return data;
}

export default Posts;
import React from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    setVoteCount: () => dispatch({ type: 'SET_VOTE_COUNT', count: '12' }),
  }
}

const AddButton = props => (
  <div className="voting">
    <button onClick={() => {
      console.log(props.setVoteCount(props.count));
    }}>
      Vote
    </button>
  </div>
);


export default connect(null, mapDispatchToProps)(AddButton);
export const setVoteCount = (id) => {
    return {
        type: "SET_VOTE_COUNT",
        count: '',
        id
    };
}
import { createStore, applyMiddleware, compose } from 'redux';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const change_counter = (state = {}, action) => {
    switch (action.type) {

        case "SET_VOTE_COUNT":
        if (state.id !== action.id) {
            return state;
        }
        return {
                ...state,
        }
        case "INCREMENT":
        if (state.id !== action.id) {
            return state;
        }
        return {
            ...state,
            count: parseInt(state.count) + 1
        };
        case "DECREMENT":
        if (state.id !== action.id) {
            return state;
        }

        return {
            ...state,
            count: parseInt(state.count) - 1
        };
        default:
        return state;
    }
    };
    let nextId = 0;
    const counters = (state = [], action) => {
        switch (action.type) {
        case "ADD_COUNTER":
            return [...state, {id: nextId++, count: 0}];
        case "SET_VOTE_COUNT":
                return [...state, {id: nextId++, count: action.count}];
        case "INCREMENT":
            return state.map(counter => change_counter(counter, action));
        case "DECREMENT":
            return state.map(counter => change_counter(counter, action));
        default:
            return state;
        }
    }
    export default createStore(counters, composeEnhancers(applyMiddleware()));
提前感谢

使用react-redux从功能组件内的存储中获取值。您也可以使用而不是
连接

我还建议添加以创建异步操作

actions.js

import React, {Component} from 'react';
import AddButton from './AddButton'

class Posts extends Component {
constructor(props) {
    super(props);

    this.state = {
        response: ''
    };
}

componentDidMount() {
    getPostAsync('/posts').then(data => this.setState({ response: data }));
}

render() {

    return (
    <div className="App">
        <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />

        {Array.isArray(this.state.response) &&
            this.state.response.map(api => <>

                { api.voteScore}
                {console.log(api.voteScore)}

                <AddButton className="voting"
                    count={api.voteScore} />
                <p> { api.title }, by { api.author } </p>
                <p> { api.body } </p>
                <p> {api.category} </p>
            </>
        )}

        </header>
    </div>
    )
}
}
async function getPostAsync(api) {
    let response = await fetch(api);
    let data = await response.json()
    return data;
}

export default Posts;
import React from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    setVoteCount: () => dispatch({ type: 'SET_VOTE_COUNT', count: '12' }),
  }
}

const AddButton = props => (
  <div className="voting">
    <button onClick={() => {
      console.log(props.setVoteCount(props.count));
    }}>
      Vote
    </button>
  </div>
);


export default connect(null, mapDispatchToProps)(AddButton);
export const setVoteCount = (id) => {
    return {
        type: "SET_VOTE_COUNT",
        count: '',
        id
    };
}
import { createStore, applyMiddleware, compose } from 'redux';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const change_counter = (state = {}, action) => {
    switch (action.type) {

        case "SET_VOTE_COUNT":
        if (state.id !== action.id) {
            return state;
        }
        return {
                ...state,
        }
        case "INCREMENT":
        if (state.id !== action.id) {
            return state;
        }
        return {
            ...state,
            count: parseInt(state.count) + 1
        };
        case "DECREMENT":
        if (state.id !== action.id) {
            return state;
        }

        return {
            ...state,
            count: parseInt(state.count) - 1
        };
        default:
        return state;
    }
    };
    let nextId = 0;
    const counters = (state = [], action) => {
        switch (action.type) {
        case "ADD_COUNTER":
            return [...state, {id: nextId++, count: 0}];
        case "SET_VOTE_COUNT":
                return [...state, {id: nextId++, count: action.count}];
        case "INCREMENT":
            return state.map(counter => change_counter(counter, action));
        case "DECREMENT":
            return state.map(counter => change_counter(counter, action));
        default:
            return state;
        }
    }
    export default createStore(counters, composeEnhancers(applyMiddleware()));
异步函数getPostAsync(api){ let response=等待获取(api); let data=wait response.json() 返回数据; } 导出常量setVoteCount=(id)=>{ 返回{ 类型:“设置投票数”, 计数:“”, 身份证件 }; } 导出常量fetchVoteCount=()=>{ 返回功能(调度){ getPostAsync('/posts')。然后(数据=>{ 调度(setVoteCount(数据)); })); }; } AddButton.js

import React, {Component} from 'react';
import AddButton from './AddButton'

class Posts extends Component {
constructor(props) {
    super(props);

    this.state = {
        response: ''
    };
}

componentDidMount() {
    getPostAsync('/posts').then(data => this.setState({ response: data }));
}

render() {

    return (
    <div className="App">
        <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />

        {Array.isArray(this.state.response) &&
            this.state.response.map(api => <>

                { api.voteScore}
                {console.log(api.voteScore)}

                <AddButton className="voting"
                    count={api.voteScore} />
                <p> { api.title }, by { api.author } </p>
                <p> { api.body } </p>
                <p> {api.category} </p>
            </>
        )}

        </header>
    </div>
    )
}
}
async function getPostAsync(api) {
    let response = await fetch(api);
    let data = await response.json()
    return data;
}

export default Posts;
import React from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    setVoteCount: () => dispatch({ type: 'SET_VOTE_COUNT', count: '12' }),
  }
}

const AddButton = props => (
  <div className="voting">
    <button onClick={() => {
      console.log(props.setVoteCount(props.count));
    }}>
      Vote
    </button>
  </div>
);


export default connect(null, mapDispatchToProps)(AddButton);
export const setVoteCount = (id) => {
    return {
        type: "SET_VOTE_COUNT",
        count: '',
        id
    };
}
import { createStore, applyMiddleware, compose } from 'redux';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const change_counter = (state = {}, action) => {
    switch (action.type) {

        case "SET_VOTE_COUNT":
        if (state.id !== action.id) {
            return state;
        }
        return {
                ...state,
        }
        case "INCREMENT":
        if (state.id !== action.id) {
            return state;
        }
        return {
            ...state,
            count: parseInt(state.count) + 1
        };
        case "DECREMENT":
        if (state.id !== action.id) {
            return state;
        }

        return {
            ...state,
            count: parseInt(state.count) - 1
        };
        default:
        return state;
    }
    };
    let nextId = 0;
    const counters = (state = [], action) => {
        switch (action.type) {
        case "ADD_COUNTER":
            return [...state, {id: nextId++, count: 0}];
        case "SET_VOTE_COUNT":
                return [...state, {id: nextId++, count: action.count}];
        case "INCREMENT":
            return state.map(counter => change_counter(counter, action));
        case "DECREMENT":
            return state.map(counter => change_counter(counter, action));
        default:
            return state;
        }
    }
    export default createStore(counters, composeEnhancers(applyMiddleware()));
从'react redux'导入{useDispatch,useSelector};
从“React”导入React;
导出默认功能AddButton(道具){
const dispatch=usedpatch();
const voteCount=useSelector(state=>state.count);
返回(
{
分派({type:'SET_VOTE_COUNT',COUNT:voteCount+1})
}}>
投票
);
}

假设“const dispach”和“const voteCount”在“const AddButton”之上,它将返回“Invalid hook call”。ESLint分析错误:“const dispach..”中出现意外标记对此表示抱歉,我键入的内容不正确。警告:收到了
子属性的NaN。但这不是我试图从API映射到存储的整数。我明白了。我建议在操作中执行异步加载,并从React组件中删除所有异步代码。我将更新我的答案。当我单击按钮仍在计票中创建NaN值时