gpt4 book ai didi

javascript - React redux reducer 从状态获取数据?

转载 作者:行者123 更新时间:2023-12-01 01:46:54 25 4
gpt4 key购买 nike

尝试使用 React 和 Redux 来从 API 获取文件列表。

在查看 react 开发工具时,我可以在那里看到我的数据,但它没有被渲染。

actions.js

export const requestFiles  = ({
type: REQUEST_FILES,
});

export const receiveFiles = (json) => ({
type: RECEIVE_FILES,
files: json,
receivedAt: Date.now()
});


export const fetchFiles = (dispatch) => {
dispatch(requestFiles);
return fetch('/api/files')
.then(response => response.json())
.then(json => dispatch(receiveFiles(json)))
};

该操作从 JSON 获取数据

enter image description here

reducer.js

const files = (state = {
isFetching: false,
items: []
}, action) => {
switch (action.type) {
case REQUEST_FILES:
return {
...state,
isFetching: true,
};
case RECEIVE_FILES:
return {
...state,
isFetching: false,
items: action.files,
lastUpdated: action.receivedAt
};
default:
return state
}
};

const filesUploaded = (state = { }, action) => {
switch (action.type) {
case RECEIVE_FILES:
case REQUEST_FILES:
return {
...state,
items: files(state[action], action)
};
default:
return state
}
};

const rootReducer = combineReducers({
filesUploaded
});

export default rootReducer

App.js

class App extends Component {
static propTypes = {
files: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired
};

componentDidMount() {
const {dispatch} = this.props;
dispatch(fetchFiles);
}

handleChange = nextSubreddit => {
};

render() {
const {files, isFetching} = this.props;
const isEmpty = files.length === 0;
console.log(`Files is empty ${isEmpty}`);
return (
<div>
<h1>Uploadr</h1>
{isEmpty
? (isFetching ? <h2>Loading...</h2> : <h2>No files.</h2>)
: <div style={{opacity: isFetching ? 0.5 : 1}}>
<Files files={files}/>
</div>
}
</div>
)
}
}

const mapStateToProps = state => {
const {uploadedFiles} = state;
const {isFetching, items: files} = uploadedFiles
|| {isFetching: true, items: []};

console.log(files);

return {
files,
isFetching,
}
};

enter image description here

操作中收到的数据,但我不确定它是否被存储或者问题是否是从 redux 存储访问它。

应用程序组件上的文件属性仍然为零,如上面的屏幕截图所示。

有什么想法吗?

最佳答案

删除您的filesUploaded reducer 。你不需要它。相反,只需使用 files 缩减器:

const rootReducer = combineReducers({
files,
});

请注意,您感兴趣的状态切片将称为files。将您的 mapStateToProps 函数更改为:

const mapStateToProps = state => {
const {isFetching, items: files} = state.files

console.log(files);

return {
files,
isFetching,
}
};

您可以在这里看到,我们获取状态的 files 切片并将其传递到您的组件中。

关于javascript - React redux reducer 从状态获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51883891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com