开始使用 React 进行 Web 货币化
在看到“网络黑客马拉松资助”的公告后,我做了一些挖掘和思考,试图更好地理解网络货币化。
如果您希望使用 React 创建一些东西,希望本快速指南可以为您节省一些入门时间。
创建一个钩子来查看用户是否通过网络获利
这是一个钩子,它将返回两个状态 -isMonetized
和loading
:
import { useEffect, useState } from 'react';
export const useMonetization = () => {
const [isMonetized, setIsMonetized] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (!document.monetization) {
// This means this user doesn't have monetization capabilities
// i.e. they don't have the Coil extension installed on their browser
setIsLoading(false);
setIsMonetized(false);
return;
}
// Note: A user could have monetization capabilities (i.e. installed Coil)
// but that doesn't mean they've actually signed up for an account!
const { state } = document.monetization;
// If the initial state is 'stopped', we can assume the user isn't
// going to pay, and so we can stop loading
if (state === 'stopped') {
setIsLoading(false);
setIsMonetized(false);
}
// We add a listener to wait for the user to start paying
document.monetization.addEventListener('monetizationstart', () => {
setIsMonetized(true);
setIsLoading(false)
});
}, []);
return { isMonetized, isLoading };
};
你可以像这样使用它:
const { isLoading, isMonetized } = useMonetization();
if (isLoading) {
// Return a spinner
} else if (isMonetized) {
// Show exclusive content
} else {
// Let the user know there is exclusive content available
}
如何在不注册 Coil 的情况下测试你的网络盈利能力
test -web-monetization提供了一个书签小工具,你可以用它来测试你的项目(向下滚动到页面的“测试用书签小工具”部分)。这使得测试 Web 货币化变得非常容易——而且它也可以与我上面描述的 React hook 配合使用。
这也意味着,如果您以这种方式设置了 Web 盈利功能,任何人都可以通过使用上面列出的书签小程序轻松绕过它。目前,Web 盈利网站上还没有服务器端示例,但希望很快就会有!
其他资源
如果您打算使用 React 或 Gatsby,那么有一些小包可能会对您有所帮助:
我非常期待看到大家为这次黑客马拉松带来的精彩创意!祝你好运!
文章来源:https://dev.to/emma/getting-started-with-web-monetization-in-react-3m4j